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 |
---|---|---|---|---|---|---|---|---|---|---|---|
ccsalespro/meta_enum | lib/meta_enum/type.rb | MetaEnum.Type.[] | def [](key)
case key
when Element, MissingElement
raise ArgumentError, "wrong type" unless key.type == self
key
when Symbol
elements_by_name.fetch(key)
else
key = normalize_value(key)
elements_by_value.fetch(key) { MissingElement.new key, self }
end
end | ruby | def [](key)
case key
when Element, MissingElement
raise ArgumentError, "wrong type" unless key.type == self
key
when Symbol
elements_by_name.fetch(key)
else
key = normalize_value(key)
elements_by_value.fetch(key) { MissingElement.new key, self }
end
end | [
"def",
"[]",
"(",
"key",
")",
"case",
"key",
"when",
"Element",
",",
"MissingElement",
"raise",
"ArgumentError",
",",
"\"wrong type\"",
"unless",
"key",
".",
"type",
"==",
"self",
"key",
"when",
"Symbol",
"elements_by_name",
".",
"fetch",
"(",
"key",
")",
"else",
"key",
"=",
"normalize_value",
"(",
"key",
")",
"elements_by_value",
".",
"fetch",
"(",
"key",
")",
"{",
"MissingElement",
".",
"new",
"key",
",",
"self",
"}",
"end",
"end"
] | Initialize takes a single hash of name to value.
e.g. MetaEnum::Type.new(red: 0, green: 1, blue: 2)
Additional data can also be associated with each value by passing an array
of [value, extra data]. This can be used for additional description or
any other reason.
e.g. MetaEnum::Type.new(small: [0, "Less than 10], large: [1, "At least 10"]
value_normalizer is a callable object that normalizes values. The default
converts all values to integers. To allow string values use method(:String).
element_class is the class with which to create elements. It should be a
sub-class of MetaEnum::Element (or otherwise match it's behavior).
[] is a "do what I mean" operator. It returns the Element from this type depending on the key.
When key is a symbol, it is considered the name of the Element to return.
Since symbols are used from code, it is considered an error if the key is
not found and it raises an exception.
When key can be converted to an integer by value_normalizer, then it is
considered the value of the Element to return. Retrieving by value is
presumed to converting from external data where a missing value should not
be considered fatal. In this case it returns a MissingElement is with value
as the key. This allows a Type to only specify the values it needs while
passing through the others unmodified.
Finally, when key is a MetaEnum::Element, it is simply returned (unless it
belongs to a different Type in which case an ArgumentError is raised).
See #values_by_number and #values_by_name for non-fuzzy value selection. | [
"Initialize",
"takes",
"a",
"single",
"hash",
"of",
"name",
"to",
"value",
"."
] | 988147e7f730625bb9e1693c06415888d4732188 | https://github.com/ccsalespro/meta_enum/blob/988147e7f730625bb9e1693c06415888d4732188/lib/meta_enum/type.rb#L80-L91 | train |
riddopic/hoodie | lib/hoodie/utils/url_helper.rb | Hoodie.UrlHelper.unshorten | def unshorten(url, opts= {})
options = {
max_level: opts.fetch(:max_level, 10),
timeout: opts.fetch(:timeout, 2),
use_cache: opts.fetch(:use_cache, true)
}
url = (url =~ /^https?:/i) ? url : "http://#{url}"
__unshorten__(url, options)
end | ruby | def unshorten(url, opts= {})
options = {
max_level: opts.fetch(:max_level, 10),
timeout: opts.fetch(:timeout, 2),
use_cache: opts.fetch(:use_cache, true)
}
url = (url =~ /^https?:/i) ? url : "http://#{url}"
__unshorten__(url, options)
end | [
"def",
"unshorten",
"(",
"url",
",",
"opts",
"=",
"{",
"}",
")",
"options",
"=",
"{",
"max_level",
":",
"opts",
".",
"fetch",
"(",
":max_level",
",",
"10",
")",
",",
"timeout",
":",
"opts",
".",
"fetch",
"(",
":timeout",
",",
"2",
")",
",",
"use_cache",
":",
"opts",
".",
"fetch",
"(",
":use_cache",
",",
"true",
")",
"}",
"url",
"=",
"(",
"url",
"=~",
"/",
"/i",
")",
"?",
"url",
":",
"\"http://#{url}\"",
"__unshorten__",
"(",
"url",
",",
"options",
")",
"end"
] | Unshorten a shortened URL.
@param url [String] A shortened URL
@param [Hash] opts
@option opts [Integer] :max_level
max redirect times
@option opts [Integer] :timeout
timeout in seconds, for every request
@option opts [Boolean] :use_cache
use cached result if available
@return Original url, a url that does not redirects | [
"Unshorten",
"a",
"shortened",
"URL",
"."
] | 921601dd4849845d3f5d3765dafcf00178b2aa66 | https://github.com/riddopic/hoodie/blob/921601dd4849845d3f5d3765dafcf00178b2aa66/lib/hoodie/utils/url_helper.rb#L61-L69 | train |
thomis/eventhub-processor | lib/eventhub/helper.rb | EventHub.Helper.format_string | def format_string(message,max_characters=80)
max_characters = 5 if max_characters < 5
m = message.gsub(/\r\n|\n|\r/m,";")
return (m[0..max_characters-4] + "...") if m.size > max_characters
return m
end | ruby | def format_string(message,max_characters=80)
max_characters = 5 if max_characters < 5
m = message.gsub(/\r\n|\n|\r/m,";")
return (m[0..max_characters-4] + "...") if m.size > max_characters
return m
end | [
"def",
"format_string",
"(",
"message",
",",
"max_characters",
"=",
"80",
")",
"max_characters",
"=",
"5",
"if",
"max_characters",
"<",
"5",
"m",
"=",
"message",
".",
"gsub",
"(",
"/",
"\\r",
"\\n",
"\\n",
"\\r",
"/m",
",",
"\";\"",
")",
"return",
"(",
"m",
"[",
"0",
"..",
"max_characters",
"-",
"4",
"]",
"+",
"\"...\"",
")",
"if",
"m",
".",
"size",
">",
"max_characters",
"return",
"m",
"end"
] | replaces CR, LF, CRLF with ";" and cut's string to requied length by adding "..." if string would be longer | [
"replaces",
"CR",
"LF",
"CRLF",
"with",
";",
"and",
"cut",
"s",
"string",
"to",
"requied",
"length",
"by",
"adding",
"...",
"if",
"string",
"would",
"be",
"longer"
] | 113ecd3aeb592e185716a7f80b0aefab57092c8c | https://github.com/thomis/eventhub-processor/blob/113ecd3aeb592e185716a7f80b0aefab57092c8c/lib/eventhub/helper.rb#L11-L16 | train |
thededlier/WatsonNLPWrapper | lib/WatsonNLPWrapper.rb | WatsonNLPWrapper.WatsonNLPApi.analyze | def analyze(text, features = default_features)
if text.nil? || features.nil?
raise ArgumentError.new(NIL_ARGUMENT_ERROR)
end
response = self.class.post(
"#{@url}/analyze?version=#{@version}",
body: {
text: text.to_s,
features: features
}.to_json,
basic_auth: auth,
headers: {
"Content-Type" => CONTENT_TYPE
}
)
response.parsed_response
end | ruby | def analyze(text, features = default_features)
if text.nil? || features.nil?
raise ArgumentError.new(NIL_ARGUMENT_ERROR)
end
response = self.class.post(
"#{@url}/analyze?version=#{@version}",
body: {
text: text.to_s,
features: features
}.to_json,
basic_auth: auth,
headers: {
"Content-Type" => CONTENT_TYPE
}
)
response.parsed_response
end | [
"def",
"analyze",
"(",
"text",
",",
"features",
"=",
"default_features",
")",
"if",
"text",
".",
"nil?",
"||",
"features",
".",
"nil?",
"raise",
"ArgumentError",
".",
"new",
"(",
"NIL_ARGUMENT_ERROR",
")",
"end",
"response",
"=",
"self",
".",
"class",
".",
"post",
"(",
"\"#{@url}/analyze?version=#{@version}\"",
",",
"body",
":",
"{",
"text",
":",
"text",
".",
"to_s",
",",
"features",
":",
"features",
"}",
".",
"to_json",
",",
"basic_auth",
":",
"auth",
",",
"headers",
":",
"{",
"\"Content-Type\"",
"=>",
"CONTENT_TYPE",
"}",
")",
"response",
".",
"parsed_response",
"end"
] | Initialize instance variables for use later
Sends a POST request to analyze text with certain features enabled | [
"Initialize",
"instance",
"variables",
"for",
"use",
"later",
"Sends",
"a",
"POST",
"request",
"to",
"analyze",
"text",
"with",
"certain",
"features",
"enabled"
] | c5b9118e7f7d91dbd95d9991bd499e1f70e26a25 | https://github.com/thededlier/WatsonNLPWrapper/blob/c5b9118e7f7d91dbd95d9991bd499e1f70e26a25/lib/WatsonNLPWrapper.rb#L23-L41 | train |
thededlier/WatsonNLPWrapper | lib/WatsonNLPWrapper.rb | WatsonNLPWrapper.WatsonNLPApi.default_features | def default_features
{
entities: {
emotion: true,
sentiment: true,
limit: 2
},
keywords: {
emotion: true,
sentiment: true,
limit: 2
}
}
end | ruby | def default_features
{
entities: {
emotion: true,
sentiment: true,
limit: 2
},
keywords: {
emotion: true,
sentiment: true,
limit: 2
}
}
end | [
"def",
"default_features",
"{",
"entities",
":",
"{",
"emotion",
":",
"true",
",",
"sentiment",
":",
"true",
",",
"limit",
":",
"2",
"}",
",",
"keywords",
":",
"{",
"emotion",
":",
"true",
",",
"sentiment",
":",
"true",
",",
"limit",
":",
"2",
"}",
"}",
"end"
] | Default features if no features specified | [
"Default",
"features",
"if",
"no",
"features",
"specified"
] | c5b9118e7f7d91dbd95d9991bd499e1f70e26a25 | https://github.com/thededlier/WatsonNLPWrapper/blob/c5b9118e7f7d91dbd95d9991bd499e1f70e26a25/lib/WatsonNLPWrapper.rb#L53-L66 | train |
garytaylor/capybara_objects | lib/capybara_objects/page_object.rb | CapybaraObjects.PageObject.visit | def visit
raise ::CapybaraObjects::Exceptions::MissingUrl unless url.present?
page.visit url
validate!
self
end | ruby | def visit
raise ::CapybaraObjects::Exceptions::MissingUrl unless url.present?
page.visit url
validate!
self
end | [
"def",
"visit",
"raise",
"::",
"CapybaraObjects",
"::",
"Exceptions",
"::",
"MissingUrl",
"unless",
"url",
".",
"present?",
"page",
".",
"visit",
"url",
"validate!",
"self",
"end"
] | Visits the pre configured URL to make this page available
@raise ::CapybaraPageObjects::Exceptions::MissingUrl
@return [::CapybaraObjects::PageObject] self - allows chaining of methods | [
"Visits",
"the",
"pre",
"configured",
"URL",
"to",
"make",
"this",
"page",
"available"
] | 7cc2998400a35ceb6f9354cdf949fc59eddcdb12 | https://github.com/garytaylor/capybara_objects/blob/7cc2998400a35ceb6f9354cdf949fc59eddcdb12/lib/capybara_objects/page_object.rb#L41-L46 | train |
belsonheng/spidercrawl | lib/spidercrawl/request.rb | Spidercrawl.Request.curl | def curl
puts "fetching #{@uri.to_s}".green.on_black
start_time = Time.now
begin
c = @c
c.url = @uri.to_s
c.perform
end_time = Time.now
case c.response_code
when 200 then
page = Page.new(@uri, response_code: c.response_code,
response_head: c.header_str,
response_body: c.body_str,
response_time: ((end_time-start_time)*1000).round,
crawled_time: (Time.now.to_f*1000).to_i)
when 300..307 then
page = Page.new(@uri, response_code: c.response_code,
response_head: c.header_str,
response_body: c.body_str,
response_time: ((end_time-start_time)*1000).round,
redirect_url: c.redirect_url)
when 404 then
page = Page.new(@uri, response_code: c.response_code,
response_time: ((end_time-start_time)*1000).round)
end
rescue Exception => e
puts e.inspect
puts e.backtrace
end
end | ruby | def curl
puts "fetching #{@uri.to_s}".green.on_black
start_time = Time.now
begin
c = @c
c.url = @uri.to_s
c.perform
end_time = Time.now
case c.response_code
when 200 then
page = Page.new(@uri, response_code: c.response_code,
response_head: c.header_str,
response_body: c.body_str,
response_time: ((end_time-start_time)*1000).round,
crawled_time: (Time.now.to_f*1000).to_i)
when 300..307 then
page = Page.new(@uri, response_code: c.response_code,
response_head: c.header_str,
response_body: c.body_str,
response_time: ((end_time-start_time)*1000).round,
redirect_url: c.redirect_url)
when 404 then
page = Page.new(@uri, response_code: c.response_code,
response_time: ((end_time-start_time)*1000).round)
end
rescue Exception => e
puts e.inspect
puts e.backtrace
end
end | [
"def",
"curl",
"puts",
"\"fetching #{@uri.to_s}\"",
".",
"green",
".",
"on_black",
"start_time",
"=",
"Time",
".",
"now",
"begin",
"c",
"=",
"@c",
"c",
".",
"url",
"=",
"@uri",
".",
"to_s",
"c",
".",
"perform",
"end_time",
"=",
"Time",
".",
"now",
"case",
"c",
".",
"response_code",
"when",
"200",
"then",
"page",
"=",
"Page",
".",
"new",
"(",
"@uri",
",",
"response_code",
":",
"c",
".",
"response_code",
",",
"response_head",
":",
"c",
".",
"header_str",
",",
"response_body",
":",
"c",
".",
"body_str",
",",
"response_time",
":",
"(",
"(",
"end_time",
"-",
"start_time",
")",
"*",
"1000",
")",
".",
"round",
",",
"crawled_time",
":",
"(",
"Time",
".",
"now",
".",
"to_f",
"*",
"1000",
")",
".",
"to_i",
")",
"when",
"300",
"..",
"307",
"then",
"page",
"=",
"Page",
".",
"new",
"(",
"@uri",
",",
"response_code",
":",
"c",
".",
"response_code",
",",
"response_head",
":",
"c",
".",
"header_str",
",",
"response_body",
":",
"c",
".",
"body_str",
",",
"response_time",
":",
"(",
"(",
"end_time",
"-",
"start_time",
")",
"*",
"1000",
")",
".",
"round",
",",
"redirect_url",
":",
"c",
".",
"redirect_url",
")",
"when",
"404",
"then",
"page",
"=",
"Page",
".",
"new",
"(",
"@uri",
",",
"response_code",
":",
"c",
".",
"response_code",
",",
"response_time",
":",
"(",
"(",
"end_time",
"-",
"start_time",
")",
"*",
"1000",
")",
".",
"round",
")",
"end",
"rescue",
"Exception",
"=>",
"e",
"puts",
"e",
".",
"inspect",
"puts",
"e",
".",
"backtrace",
"end",
"end"
] | Fetch a page from the given url using libcurl | [
"Fetch",
"a",
"page",
"from",
"the",
"given",
"url",
"using",
"libcurl"
] | 195b067f551597657ad61251dc8d485ec0b0b9c7 | https://github.com/belsonheng/spidercrawl/blob/195b067f551597657ad61251dc8d485ec0b0b9c7/lib/spidercrawl/request.rb#L32-L61 | train |
barkerest/incline | lib/incline/validators/email_validator.rb | Incline.EmailValidator.validate_each | def validate_each(record, attribute, value)
unless value.blank?
record.errors[attribute] << (options[:message] || 'is not a valid email address') unless value =~ VALID_EMAIL_REGEX
end
end | ruby | def validate_each(record, attribute, value)
unless value.blank?
record.errors[attribute] << (options[:message] || 'is not a valid email address') unless value =~ VALID_EMAIL_REGEX
end
end | [
"def",
"validate_each",
"(",
"record",
",",
"attribute",
",",
"value",
")",
"unless",
"value",
".",
"blank?",
"record",
".",
"errors",
"[",
"attribute",
"]",
"<<",
"(",
"options",
"[",
":message",
"]",
"||",
"'is not a valid email address'",
")",
"unless",
"value",
"=~",
"VALID_EMAIL_REGEX",
"end",
"end"
] | Validates attributes to determine if they contain valid email addresses.
Does not perform an in depth check, but does verify that the format is valid. | [
"Validates",
"attributes",
"to",
"determine",
"if",
"they",
"contain",
"valid",
"email",
"addresses",
"."
] | 1ff08db7aa8ab7f86b223268b700bc67d15bb8aa | https://github.com/barkerest/incline/blob/1ff08db7aa8ab7f86b223268b700bc67d15bb8aa/lib/incline/validators/email_validator.rb#L29-L33 | train |
riddopic/garcun | lib/garcon/utility/interpolation.rb | Garcon.Interpolation.interpolate | def interpolate(item = self, parent = nil)
item = render item, parent
item.is_a?(Hash) ? ::Mash.new(item) : item
end | ruby | def interpolate(item = self, parent = nil)
item = render item, parent
item.is_a?(Hash) ? ::Mash.new(item) : item
end | [
"def",
"interpolate",
"(",
"item",
"=",
"self",
",",
"parent",
"=",
"nil",
")",
"item",
"=",
"render",
"item",
",",
"parent",
"item",
".",
"is_a?",
"(",
"Hash",
")",
"?",
"::",
"Mash",
".",
"new",
"(",
"item",
")",
":",
"item",
"end"
] | Interpolate provides a means of externally using Ruby string
interpolation mechinism.
@example
node[:ldap][:basedir] = '/opt'
node[:ldap][:homedir] = '%{basedir}/openldap/slap/happy'
interpolate(node[:ldap])[:homedir] # => "/opt/openldap/slap/happy"
@param [String] item
The string to interpolate.
@param [String, Hash] parent
The string used for substitution.
@return [String]
The interpolated string.
@api public | [
"Interpolate",
"provides",
"a",
"means",
"of",
"externally",
"using",
"Ruby",
"string",
"interpolation",
"mechinism",
"."
] | c2409bd8cf9c14b967a719810dab5269d69b42de | https://github.com/riddopic/garcun/blob/c2409bd8cf9c14b967a719810dab5269d69b42de/lib/garcon/utility/interpolation.rb#L44-L47 | train |
riddopic/garcun | lib/garcon/utility/interpolation.rb | Garcon.Interpolation.render | def render(item, parent = nil)
item = item.to_hash if item.respond_to?(:to_hash)
if item.is_a?(Hash)
item = item.inject({}) { |memo, (k,v)| memo[sym(k)] = v; memo }
item.inject({}) {|memo, (k,v)| memo[sym(k)] = render(v, item); memo}
elsif item.is_a?(Array)
item.map { |i| render(i, parent) }
elsif item.is_a?(String)
item % parent rescue item
else
item
end
end | ruby | def render(item, parent = nil)
item = item.to_hash if item.respond_to?(:to_hash)
if item.is_a?(Hash)
item = item.inject({}) { |memo, (k,v)| memo[sym(k)] = v; memo }
item.inject({}) {|memo, (k,v)| memo[sym(k)] = render(v, item); memo}
elsif item.is_a?(Array)
item.map { |i| render(i, parent) }
elsif item.is_a?(String)
item % parent rescue item
else
item
end
end | [
"def",
"render",
"(",
"item",
",",
"parent",
"=",
"nil",
")",
"item",
"=",
"item",
".",
"to_hash",
"if",
"item",
".",
"respond_to?",
"(",
":to_hash",
")",
"if",
"item",
".",
"is_a?",
"(",
"Hash",
")",
"item",
"=",
"item",
".",
"inject",
"(",
"{",
"}",
")",
"{",
"|",
"memo",
",",
"(",
"k",
",",
"v",
")",
"|",
"memo",
"[",
"sym",
"(",
"k",
")",
"]",
"=",
"v",
";",
"memo",
"}",
"item",
".",
"inject",
"(",
"{",
"}",
")",
"{",
"|",
"memo",
",",
"(",
"k",
",",
"v",
")",
"|",
"memo",
"[",
"sym",
"(",
"k",
")",
"]",
"=",
"render",
"(",
"v",
",",
"item",
")",
";",
"memo",
"}",
"elsif",
"item",
".",
"is_a?",
"(",
"Array",
")",
"item",
".",
"map",
"{",
"|",
"i",
"|",
"render",
"(",
"i",
",",
"parent",
")",
"}",
"elsif",
"item",
".",
"is_a?",
"(",
"String",
")",
"item",
"%",
"parent",
"rescue",
"item",
"else",
"item",
"end",
"end"
] | Provides recursive interpolation of node objects, using standard
string interpolation methods.
@param [String] item
The string to interpolate.
@param [String, Hash] parent
The string used for substitution.
@return [String]
@api private | [
"Provides",
"recursive",
"interpolation",
"of",
"node",
"objects",
"using",
"standard",
"string",
"interpolation",
"methods",
"."
] | c2409bd8cf9c14b967a719810dab5269d69b42de | https://github.com/riddopic/garcun/blob/c2409bd8cf9c14b967a719810dab5269d69b42de/lib/garcon/utility/interpolation.rb#L76-L88 | train |
chrisjones-tripletri/action_command | lib/action_command/executable_transaction.rb | ActionCommand.ExecutableTransaction.execute | def execute(result)
if ActiveRecord::Base.connection.open_transactions >= 1
super(result)
else
result.info('start_transaction')
ActiveRecord::Base.transaction do
super(result)
if result.ok?
result.info('end_transaction')
else
result.info('rollback_transaction')
raise ActiveRecord::Rollback, 'rollback transaction'
end
end
end
end | ruby | def execute(result)
if ActiveRecord::Base.connection.open_transactions >= 1
super(result)
else
result.info('start_transaction')
ActiveRecord::Base.transaction do
super(result)
if result.ok?
result.info('end_transaction')
else
result.info('rollback_transaction')
raise ActiveRecord::Rollback, 'rollback transaction'
end
end
end
end | [
"def",
"execute",
"(",
"result",
")",
"if",
"ActiveRecord",
"::",
"Base",
".",
"connection",
".",
"open_transactions",
">=",
"1",
"super",
"(",
"result",
")",
"else",
"result",
".",
"info",
"(",
"'start_transaction'",
")",
"ActiveRecord",
"::",
"Base",
".",
"transaction",
"do",
"super",
"(",
"result",
")",
"if",
"result",
".",
"ok?",
"result",
".",
"info",
"(",
"'end_transaction'",
")",
"else",
"result",
".",
"info",
"(",
"'rollback_transaction'",
")",
"raise",
"ActiveRecord",
"::",
"Rollback",
",",
"'rollback transaction'",
"end",
"end",
"end",
"end"
] | starts a transaction only if we are not already within one. | [
"starts",
"a",
"transaction",
"only",
"if",
"we",
"are",
"not",
"already",
"within",
"one",
"."
] | 9b9a8ba30e407ca6d88a62a164d1dc22ba149874 | https://github.com/chrisjones-tripletri/action_command/blob/9b9a8ba30e407ca6d88a62a164d1dc22ba149874/lib/action_command/executable_transaction.rb#L8-L23 | train |
hongshu-corp/ule_page | lib/ule_page/site_prism_extender.rb | UlePage.SitePrismExtender.element_collection | def element_collection(collection_name, *find_args)
build collection_name, *find_args do
define_method collection_name.to_s do |*runtime_args, &element_block|
self.class.raise_if_block(self, collection_name.to_s, !element_block.nil?)
page.all(*find_args)
end
end
end | ruby | def element_collection(collection_name, *find_args)
build collection_name, *find_args do
define_method collection_name.to_s do |*runtime_args, &element_block|
self.class.raise_if_block(self, collection_name.to_s, !element_block.nil?)
page.all(*find_args)
end
end
end | [
"def",
"element_collection",
"(",
"collection_name",
",",
"*",
"find_args",
")",
"build",
"collection_name",
",",
"*",
"find_args",
"do",
"define_method",
"collection_name",
".",
"to_s",
"do",
"|",
"*",
"runtime_args",
",",
"&",
"element_block",
"|",
"self",
".",
"class",
".",
"raise_if_block",
"(",
"self",
",",
"collection_name",
".",
"to_s",
",",
"!",
"element_block",
".",
"nil?",
")",
"page",
".",
"all",
"(",
"*",
"find_args",
")",
"end",
"end",
"end"
] | why define this method?
if we use the elements method directly, it will be conflicted with RSpec.Mather.BuiltIn.All.elements.
I have not found one good method to solve the confliction. | [
"why",
"define",
"this",
"method?",
"if",
"we",
"use",
"the",
"elements",
"method",
"directly",
"it",
"will",
"be",
"conflicted",
"with",
"RSpec",
".",
"Mather",
".",
"BuiltIn",
".",
"All",
".",
"elements",
".",
"I",
"have",
"not",
"found",
"one",
"good",
"method",
"to",
"solve",
"the",
"confliction",
"."
] | 599a1c1eb5c2df3b38b96896942d280284fd8ffa | https://github.com/hongshu-corp/ule_page/blob/599a1c1eb5c2df3b38b96896942d280284fd8ffa/lib/ule_page/site_prism_extender.rb#L11-L18 | train |
hongshu-corp/ule_page | lib/ule_page/site_prism_extender.rb | UlePage.SitePrismExtender.define_elements_js | def define_elements_js(model_class, excluded_props = [])
attributes = model_class.new.attributes.keys
attributes.each do |attri|
unless excluded_props.include? attri
selector = "#"+attri
# self.class.send "element", attri.to_sym, selector
element attri, selector
end
end
end | ruby | def define_elements_js(model_class, excluded_props = [])
attributes = model_class.new.attributes.keys
attributes.each do |attri|
unless excluded_props.include? attri
selector = "#"+attri
# self.class.send "element", attri.to_sym, selector
element attri, selector
end
end
end | [
"def",
"define_elements_js",
"(",
"model_class",
",",
"excluded_props",
"=",
"[",
"]",
")",
"attributes",
"=",
"model_class",
".",
"new",
".",
"attributes",
".",
"keys",
"attributes",
".",
"each",
"do",
"|",
"attri",
"|",
"unless",
"excluded_props",
".",
"include?",
"attri",
"selector",
"=",
"\"#\"",
"+",
"attri",
"element",
"attri",
",",
"selector",
"end",
"end",
"end"
] | instead of the rails traditional form
in js mode, there is no prefix before the element name | [
"instead",
"of",
"the",
"rails",
"traditional",
"form",
"in",
"js",
"mode",
"there",
"is",
"no",
"prefix",
"before",
"the",
"element",
"name"
] | 599a1c1eb5c2df3b38b96896942d280284fd8ffa | https://github.com/hongshu-corp/ule_page/blob/599a1c1eb5c2df3b38b96896942d280284fd8ffa/lib/ule_page/site_prism_extender.rb#L66-L77 | train |
spiegela/MultiBitField | lib/multi_bit_field.rb | MultiBitField.ClassMethods.range_for | def range_for column_name, field_name
column = @@bitfields[column_name]
raise ArgumentError, "Unknown column for bitfield: #{column_name}" if column.nil?
return column[field_name] if column[field_name]
raise ArugmentError, "Unknown field: #{field_name} for column #{column_name}"
end | ruby | def range_for column_name, field_name
column = @@bitfields[column_name]
raise ArgumentError, "Unknown column for bitfield: #{column_name}" if column.nil?
return column[field_name] if column[field_name]
raise ArugmentError, "Unknown field: #{field_name} for column #{column_name}"
end | [
"def",
"range_for",
"column_name",
",",
"field_name",
"column",
"=",
"@@bitfields",
"[",
"column_name",
"]",
"raise",
"ArgumentError",
",",
"\"Unknown column for bitfield: #{column_name}\"",
"if",
"column",
".",
"nil?",
"return",
"column",
"[",
"field_name",
"]",
"if",
"column",
"[",
"field_name",
"]",
"raise",
"ArugmentError",
",",
"\"Unknown field: #{field_name} for column #{column_name}\"",
"end"
] | Returns the column by name
+column_for
@param [ Symbol ] column_name column name that stores the bitfield integer | [
"Returns",
"the",
"column",
"by",
"name"
] | 53674ba73caea8d871510d02271b71edaa1335f1 | https://github.com/spiegela/MultiBitField/blob/53674ba73caea8d871510d02271b71edaa1335f1/lib/multi_bit_field.rb#L72-L77 | train |
spiegela/MultiBitField | lib/multi_bit_field.rb | MultiBitField.ClassMethods.reset_mask_for | def reset_mask_for column_name, *fields
fields = bitfields if fields.empty?
max = bitfield_max(column_name)
(0..max).sum{|i| 2 ** i} - only_mask_for(column_name, *fields)
end | ruby | def reset_mask_for column_name, *fields
fields = bitfields if fields.empty?
max = bitfield_max(column_name)
(0..max).sum{|i| 2 ** i} - only_mask_for(column_name, *fields)
end | [
"def",
"reset_mask_for",
"column_name",
",",
"*",
"fields",
"fields",
"=",
"bitfields",
"if",
"fields",
".",
"empty?",
"max",
"=",
"bitfield_max",
"(",
"column_name",
")",
"(",
"0",
"..",
"max",
")",
".",
"sum",
"{",
"|",
"i",
"|",
"2",
"**",
"i",
"}",
"-",
"only_mask_for",
"(",
"column_name",
",",
"*",
"fields",
")",
"end"
] | Returns a "reset mask" for a list of fields
+reset_mask_for :fields
@example
user.reset_mask_for :field
@param [ Symbol ] column name of the column these fields are in
@param [ Symbol ] field(s) name of the field(s) for the mask | [
"Returns",
"a",
"reset",
"mask",
"for",
"a",
"list",
"of",
"fields"
] | 53674ba73caea8d871510d02271b71edaa1335f1 | https://github.com/spiegela/MultiBitField/blob/53674ba73caea8d871510d02271b71edaa1335f1/lib/multi_bit_field.rb#L88-L92 | train |
spiegela/MultiBitField | lib/multi_bit_field.rb | MultiBitField.ClassMethods.increment_mask_for | def increment_mask_for column_name, *fields
fields = bitfields if fields.empty?
column = @@bitfields[column_name]
raise ArgumentError, "Unknown column for bitfield: #{column_name}" if column.nil?
fields.sum do |field_name|
raise ArugmentError, "Unknown field: #{field_name} for column #{column_name}" if column[field_name].nil?
2 ** (bitfield_max(column_name) - column[field_name].last)
end
end | ruby | def increment_mask_for column_name, *fields
fields = bitfields if fields.empty?
column = @@bitfields[column_name]
raise ArgumentError, "Unknown column for bitfield: #{column_name}" if column.nil?
fields.sum do |field_name|
raise ArugmentError, "Unknown field: #{field_name} for column #{column_name}" if column[field_name].nil?
2 ** (bitfield_max(column_name) - column[field_name].last)
end
end | [
"def",
"increment_mask_for",
"column_name",
",",
"*",
"fields",
"fields",
"=",
"bitfields",
"if",
"fields",
".",
"empty?",
"column",
"=",
"@@bitfields",
"[",
"column_name",
"]",
"raise",
"ArgumentError",
",",
"\"Unknown column for bitfield: #{column_name}\"",
"if",
"column",
".",
"nil?",
"fields",
".",
"sum",
"do",
"|",
"field_name",
"|",
"raise",
"ArugmentError",
",",
"\"Unknown field: #{field_name} for column #{column_name}\"",
"if",
"column",
"[",
"field_name",
"]",
".",
"nil?",
"2",
"**",
"(",
"bitfield_max",
"(",
"column_name",
")",
"-",
"column",
"[",
"field_name",
"]",
".",
"last",
")",
"end",
"end"
] | Returns an "increment mask" for a list of fields
+increment_mask_for :fields
@example
user.increment_mask_for :field
@param [ Symbol ] column name of the column these fields are in
@param [ Symbol ] field(s) name of the field(s) for the mask | [
"Returns",
"an",
"increment",
"mask",
"for",
"a",
"list",
"of",
"fields"
] | 53674ba73caea8d871510d02271b71edaa1335f1 | https://github.com/spiegela/MultiBitField/blob/53674ba73caea8d871510d02271b71edaa1335f1/lib/multi_bit_field.rb#L103-L111 | train |
spiegela/MultiBitField | lib/multi_bit_field.rb | MultiBitField.ClassMethods.only_mask_for | def only_mask_for column_name, *fields
fields = bitfields if fields.empty?
column = @@bitfields[column_name]
max = bitfield_max(column_name)
raise ArgumentError, "Unknown column for bitfield: #{column_name}" if column.nil?
column.sum do |field_name, range|
fields.include?(field_name) ? range.invert(max).sum{|i| 2 ** i} : 0
end
# fields.inject("0" * (bitfield_max(column_name) + 1)) do |mask, field_name|
# raise ArugmentError, "Unknown field: #{field_name} for column #{column_name}" if column[field_name].nil?
# range = column[field_name]
# mask[range] = "1" * range.count
# mask
# end.to_i(2)
end | ruby | def only_mask_for column_name, *fields
fields = bitfields if fields.empty?
column = @@bitfields[column_name]
max = bitfield_max(column_name)
raise ArgumentError, "Unknown column for bitfield: #{column_name}" if column.nil?
column.sum do |field_name, range|
fields.include?(field_name) ? range.invert(max).sum{|i| 2 ** i} : 0
end
# fields.inject("0" * (bitfield_max(column_name) + 1)) do |mask, field_name|
# raise ArugmentError, "Unknown field: #{field_name} for column #{column_name}" if column[field_name].nil?
# range = column[field_name]
# mask[range] = "1" * range.count
# mask
# end.to_i(2)
end | [
"def",
"only_mask_for",
"column_name",
",",
"*",
"fields",
"fields",
"=",
"bitfields",
"if",
"fields",
".",
"empty?",
"column",
"=",
"@@bitfields",
"[",
"column_name",
"]",
"max",
"=",
"bitfield_max",
"(",
"column_name",
")",
"raise",
"ArgumentError",
",",
"\"Unknown column for bitfield: #{column_name}\"",
"if",
"column",
".",
"nil?",
"column",
".",
"sum",
"do",
"|",
"field_name",
",",
"range",
"|",
"fields",
".",
"include?",
"(",
"field_name",
")",
"?",
"range",
".",
"invert",
"(",
"max",
")",
".",
"sum",
"{",
"|",
"i",
"|",
"2",
"**",
"i",
"}",
":",
"0",
"end",
"end"
] | Returns an "only mask" for a list of fields
+only_mask_for :fields
@example
user.only_mask_for :field
@param [ Symbol ] column name of the column these fields are in
@param [ Symbol ] field(s) name of the field(s) for the mask | [
"Returns",
"an",
"only",
"mask",
"for",
"a",
"list",
"of",
"fields"
] | 53674ba73caea8d871510d02271b71edaa1335f1 | https://github.com/spiegela/MultiBitField/blob/53674ba73caea8d871510d02271b71edaa1335f1/lib/multi_bit_field.rb#L122-L138 | train |
spiegela/MultiBitField | lib/multi_bit_field.rb | MultiBitField.ClassMethods.count_by | def count_by column_name, field
inc = increment_mask_for column_name, field
only = only_mask_for column_name, field
# Create super-special-bitfield-grouping-query w/ AREL
sql = arel_table.
project("count(#{primary_key}) as #{field}_count, (#{column_name} & #{only})/#{inc} as #{field}").
group(field).to_sql
connection.send :select, sql, 'AREL' # Execute the query
end | ruby | def count_by column_name, field
inc = increment_mask_for column_name, field
only = only_mask_for column_name, field
# Create super-special-bitfield-grouping-query w/ AREL
sql = arel_table.
project("count(#{primary_key}) as #{field}_count, (#{column_name} & #{only})/#{inc} as #{field}").
group(field).to_sql
connection.send :select, sql, 'AREL' # Execute the query
end | [
"def",
"count_by",
"column_name",
",",
"field",
"inc",
"=",
"increment_mask_for",
"column_name",
",",
"field",
"only",
"=",
"only_mask_for",
"column_name",
",",
"field",
"sql",
"=",
"arel_table",
".",
"project",
"(",
"\"count(#{primary_key}) as #{field}_count, (#{column_name} & #{only})/#{inc} as #{field}\"",
")",
".",
"group",
"(",
"field",
")",
".",
"to_sql",
"connection",
".",
"send",
":select",
",",
"sql",
",",
"'AREL'",
"end"
] | Counts resources grouped by a bitfield
+count_by :column, :fields
@example
user.count_by :counter, :monthly
@param [ Symbol ] column name of the column these fields are in
@param [ Symbol ] field(s) name of the field(s) to reset | [
"Counts",
"resources",
"grouped",
"by",
"a",
"bitfield"
] | 53674ba73caea8d871510d02271b71edaa1335f1 | https://github.com/spiegela/MultiBitField/blob/53674ba73caea8d871510d02271b71edaa1335f1/lib/multi_bit_field.rb#L179-L187 | train |
spiegela/MultiBitField | lib/multi_bit_field.rb | MultiBitField.InstanceMethods.reset_bitfields | def reset_bitfields column_name, *fields
mask = self.class.reset_mask_for column_name, *fields
self[column_name] = self[column_name] & mask
save
end | ruby | def reset_bitfields column_name, *fields
mask = self.class.reset_mask_for column_name, *fields
self[column_name] = self[column_name] & mask
save
end | [
"def",
"reset_bitfields",
"column_name",
",",
"*",
"fields",
"mask",
"=",
"self",
".",
"class",
".",
"reset_mask_for",
"column_name",
",",
"*",
"fields",
"self",
"[",
"column_name",
"]",
"=",
"self",
"[",
"column_name",
"]",
"&",
"mask",
"save",
"end"
] | Sets one or more bitfields to 0 within a column
+reset_bitfield :column, :fields
@example
user.reset_bitfield :column, :daily, :monthly
@param [ Symbol ] column name of the column these fields are in
@param [ Symbol ] field(s) name of the field(s) to reset | [
"Sets",
"one",
"or",
"more",
"bitfields",
"to",
"0",
"within",
"a",
"column"
] | 53674ba73caea8d871510d02271b71edaa1335f1 | https://github.com/spiegela/MultiBitField/blob/53674ba73caea8d871510d02271b71edaa1335f1/lib/multi_bit_field.rb#L210-L214 | train |
spiegela/MultiBitField | lib/multi_bit_field.rb | MultiBitField.InstanceMethods.increment_bitfields | def increment_bitfields column_name, *fields
mask = self.class.increment_mask_for column_name, *fields
self[column_name] = self[column_name] += mask
save
end | ruby | def increment_bitfields column_name, *fields
mask = self.class.increment_mask_for column_name, *fields
self[column_name] = self[column_name] += mask
save
end | [
"def",
"increment_bitfields",
"column_name",
",",
"*",
"fields",
"mask",
"=",
"self",
".",
"class",
".",
"increment_mask_for",
"column_name",
",",
"*",
"fields",
"self",
"[",
"column_name",
"]",
"=",
"self",
"[",
"column_name",
"]",
"+=",
"mask",
"save",
"end"
] | Increases one or more bitfields by 1 value
+increment_bitfield :column, :fields
@example
user.increment_bitfield :column, :daily, :monthly
@param [ Symbol ] column name of the column these fields are in
@param [ Symbol ] field(s) name of the field(s) to reset | [
"Increases",
"one",
"or",
"more",
"bitfields",
"by",
"1",
"value"
] | 53674ba73caea8d871510d02271b71edaa1335f1 | https://github.com/spiegela/MultiBitField/blob/53674ba73caea8d871510d02271b71edaa1335f1/lib/multi_bit_field.rb#L226-L230 | train |
openstax/connect-rails | lib/openstax/connect/current_user_manager.rb | OpenStax::Connect.CurrentUserManager.connect_current_user= | def connect_current_user=(user)
@connect_current_user = user || User.anonymous
@app_current_user = user_provider.connect_user_to_app_user(@connect_current_user)
if @connect_current_user.is_anonymous?
@session[:user_id] = nil
@cookies.delete(:secure_user_id)
else
@session[:user_id] = @connect_current_user.id
@cookies.signed[:secure_user_id] = {secure: true, value: "secure#{@connect_current_user.id}"}
end
@connect_current_user
end | ruby | def connect_current_user=(user)
@connect_current_user = user || User.anonymous
@app_current_user = user_provider.connect_user_to_app_user(@connect_current_user)
if @connect_current_user.is_anonymous?
@session[:user_id] = nil
@cookies.delete(:secure_user_id)
else
@session[:user_id] = @connect_current_user.id
@cookies.signed[:secure_user_id] = {secure: true, value: "secure#{@connect_current_user.id}"}
end
@connect_current_user
end | [
"def",
"connect_current_user",
"=",
"(",
"user",
")",
"@connect_current_user",
"=",
"user",
"||",
"User",
".",
"anonymous",
"@app_current_user",
"=",
"user_provider",
".",
"connect_user_to_app_user",
"(",
"@connect_current_user",
")",
"if",
"@connect_current_user",
".",
"is_anonymous?",
"@session",
"[",
":user_id",
"]",
"=",
"nil",
"@cookies",
".",
"delete",
"(",
":secure_user_id",
")",
"else",
"@session",
"[",
":user_id",
"]",
"=",
"@connect_current_user",
".",
"id",
"@cookies",
".",
"signed",
"[",
":secure_user_id",
"]",
"=",
"{",
"secure",
":",
"true",
",",
"value",
":",
"\"secure#{@connect_current_user.id}\"",
"}",
"end",
"@connect_current_user",
"end"
] | Sets the current connect user, updates the app user, and also updates the
session and cookie state. | [
"Sets",
"the",
"current",
"connect",
"user",
"updates",
"the",
"app",
"user",
"and",
"also",
"updates",
"the",
"session",
"and",
"cookie",
"state",
"."
] | 4ac16cfa4316f9f0ba4df8b8d6dd960f90dbb962 | https://github.com/openstax/connect-rails/blob/4ac16cfa4316f9f0ba4df8b8d6dd960f90dbb962/lib/openstax/connect/current_user_manager.rb#L80-L93 | train |
vidibus/vidibus-encoder | lib/vidibus/encoder.rb | Vidibus.Encoder.register_format | def register_format(name, processor)
unless processor.new.is_a?(Vidibus::Encoder::Base)
raise(ArgumentError, 'The processor must inherit Vidibus::Encoder::Base')
end
@formats ||= {}
@formats[name] = processor
end | ruby | def register_format(name, processor)
unless processor.new.is_a?(Vidibus::Encoder::Base)
raise(ArgumentError, 'The processor must inherit Vidibus::Encoder::Base')
end
@formats ||= {}
@formats[name] = processor
end | [
"def",
"register_format",
"(",
"name",
",",
"processor",
")",
"unless",
"processor",
".",
"new",
".",
"is_a?",
"(",
"Vidibus",
"::",
"Encoder",
"::",
"Base",
")",
"raise",
"(",
"ArgumentError",
",",
"'The processor must inherit Vidibus::Encoder::Base'",
")",
"end",
"@formats",
"||=",
"{",
"}",
"@formats",
"[",
"name",
"]",
"=",
"processor",
"end"
] | Register a new encoder format. | [
"Register",
"a",
"new",
"encoder",
"format",
"."
] | 71f682eeb28703b811fd7cd9f9b1b127a7c691c3 | https://github.com/vidibus/vidibus-encoder/blob/71f682eeb28703b811fd7cd9f9b1b127a7c691c3/lib/vidibus/encoder.rb#L23-L29 | train |
cknadler/rcomp | lib/rcomp/conf.rb | RComp.Conf.read_conf_file | def read_conf_file
conf = {}
if File.exists?(CONF_PATH) && File.size?(CONF_PATH)
# Store valid conf keys
YAML.load_file(CONF_PATH).each do |key, value|
if VALID_KEYS.include? key
conf[key] = value
else
say "Invalid configuration key: #{key}"
end
end
end
conf
end | ruby | def read_conf_file
conf = {}
if File.exists?(CONF_PATH) && File.size?(CONF_PATH)
# Store valid conf keys
YAML.load_file(CONF_PATH).each do |key, value|
if VALID_KEYS.include? key
conf[key] = value
else
say "Invalid configuration key: #{key}"
end
end
end
conf
end | [
"def",
"read_conf_file",
"conf",
"=",
"{",
"}",
"if",
"File",
".",
"exists?",
"(",
"CONF_PATH",
")",
"&&",
"File",
".",
"size?",
"(",
"CONF_PATH",
")",
"YAML",
".",
"load_file",
"(",
"CONF_PATH",
")",
".",
"each",
"do",
"|",
"key",
",",
"value",
"|",
"if",
"VALID_KEYS",
".",
"include?",
"key",
"conf",
"[",
"key",
"]",
"=",
"value",
"else",
"say",
"\"Invalid configuration key: #{key}\"",
"end",
"end",
"end",
"conf",
"end"
] | Read the config options from RComp's configuration file
Returns a Hash of config options | [
"Read",
"the",
"config",
"options",
"from",
"RComp",
"s",
"configuration",
"file"
] | 76fe71e1ef3b13923738ea6ab9cd502fe2f64f51 | https://github.com/cknadler/rcomp/blob/76fe71e1ef3b13923738ea6ab9cd502fe2f64f51/lib/rcomp/conf.rb#L66-L79 | train |
plukevdh/monet | lib/monet/baseline_control.rb | Monet.BaselineControl.rebase | def rebase(image)
new_path = @router.baseline_dir(image.name)
create_path_for_file(new_path)
FileUtils.move(image.path, new_path)
Monet::Image.new(new_path)
end | ruby | def rebase(image)
new_path = @router.baseline_dir(image.name)
create_path_for_file(new_path)
FileUtils.move(image.path, new_path)
Monet::Image.new(new_path)
end | [
"def",
"rebase",
"(",
"image",
")",
"new_path",
"=",
"@router",
".",
"baseline_dir",
"(",
"image",
".",
"name",
")",
"create_path_for_file",
"(",
"new_path",
")",
"FileUtils",
".",
"move",
"(",
"image",
".",
"path",
",",
"new_path",
")",
"Monet",
"::",
"Image",
".",
"new",
"(",
"new_path",
")",
"end"
] | returns a new image for the moved image | [
"returns",
"a",
"new",
"image",
"for",
"the",
"moved",
"image"
] | 4e2a413e70371d0b3a6b05a2675c7b4a28e6c30b | https://github.com/plukevdh/monet/blob/4e2a413e70371d0b3a6b05a2675c7b4a28e6c30b/lib/monet/baseline_control.rb#L67-L74 | train |
phildionne/associates | lib/associates/persistence.rb | Associates.Persistence.save | def save(*args)
return false unless valid?
ActiveRecord::Base.transaction do
begin
associates.all? do |associate|
send(associate.name).send(:save!, *args)
end
rescue ActiveRecord::RecordInvalid
false
end
end
end | ruby | def save(*args)
return false unless valid?
ActiveRecord::Base.transaction do
begin
associates.all? do |associate|
send(associate.name).send(:save!, *args)
end
rescue ActiveRecord::RecordInvalid
false
end
end
end | [
"def",
"save",
"(",
"*",
"args",
")",
"return",
"false",
"unless",
"valid?",
"ActiveRecord",
"::",
"Base",
".",
"transaction",
"do",
"begin",
"associates",
".",
"all?",
"do",
"|",
"associate",
"|",
"send",
"(",
"associate",
".",
"name",
")",
".",
"send",
"(",
":save!",
",",
"*",
"args",
")",
"end",
"rescue",
"ActiveRecord",
"::",
"RecordInvalid",
"false",
"end",
"end",
"end"
] | Persists each associated model
@return [Boolean] Wether or not all models are valid and persited | [
"Persists",
"each",
"associated",
"model"
] | 630edcc47340a73ad787feaf2cdf326b4487bb9f | https://github.com/phildionne/associates/blob/630edcc47340a73ad787feaf2cdf326b4487bb9f/lib/associates/persistence.rb#L16-L28 | train |
rlister/auger | lib/auger/project.rb | Auger.Project.connections | def connections(*roles)
if roles.empty?
@connections
else
@connections.select { |c| c.roles.empty? or !(c.roles & roles).empty? }
end
end | ruby | def connections(*roles)
if roles.empty?
@connections
else
@connections.select { |c| c.roles.empty? or !(c.roles & roles).empty? }
end
end | [
"def",
"connections",
"(",
"*",
"roles",
")",
"if",
"roles",
".",
"empty?",
"@connections",
"else",
"@connections",
".",
"select",
"{",
"|",
"c",
"|",
"c",
".",
"roles",
".",
"empty?",
"or",
"!",
"(",
"c",
".",
"roles",
"&",
"roles",
")",
".",
"empty?",
"}",
"end",
"end"
] | return all connections, or those matching list of roles;
connections with no roles match all, or find intersection with roles list | [
"return",
"all",
"connections",
"or",
"those",
"matching",
"list",
"of",
"roles",
";",
"connections",
"with",
"no",
"roles",
"match",
"all",
"or",
"find",
"intersection",
"with",
"roles",
"list"
] | 45e220668251834cdf0cec78da5918aee6418d8e | https://github.com/rlister/auger/blob/45e220668251834cdf0cec78da5918aee6418d8e/lib/auger/project.rb#L54-L60 | train |
arvicco/poster | lib/poster/rss.rb | Poster.Rss.extract_data | def extract_data item, text_limit: 1200
link = item.link
desc = item.description
title = item.title.force_encoding('UTF-8')
# Extract main image
case
when desc.match(/\|.*\|/m)
img, terms, text = desc.split('|')
when desc.include?('|')
img, text = desc.split('|')
terms = nil
when desc.match(/<img.*?src="(.*?)\"/)
img = desc.match(/<img.*?src="(.*?)\"/)[1]
text = desc
terms = nil
else
img, terms, text = nil, nil, desc
end
# Extract categories
categories =
if terms
terms.split(/term_group: .*\n/).
select {|g| g.match /taxonomy: category/}.
map {|c| c.match( /name: (.*)\n/)[1]}
else
[]
end
# Crop text
short_text = strip_tags(text)[0..text_limit]
# Normalize newlines
short_text = short_text.gsub(/\A\s+/,"").gsub(/\n+/,"\n\n")
# Right-strip to end of last paragraph
short_text = short_text[0..short_text.rindex(/\.\n/)]
[title, link, img, short_text, categories]
end | ruby | def extract_data item, text_limit: 1200
link = item.link
desc = item.description
title = item.title.force_encoding('UTF-8')
# Extract main image
case
when desc.match(/\|.*\|/m)
img, terms, text = desc.split('|')
when desc.include?('|')
img, text = desc.split('|')
terms = nil
when desc.match(/<img.*?src="(.*?)\"/)
img = desc.match(/<img.*?src="(.*?)\"/)[1]
text = desc
terms = nil
else
img, terms, text = nil, nil, desc
end
# Extract categories
categories =
if terms
terms.split(/term_group: .*\n/).
select {|g| g.match /taxonomy: category/}.
map {|c| c.match( /name: (.*)\n/)[1]}
else
[]
end
# Crop text
short_text = strip_tags(text)[0..text_limit]
# Normalize newlines
short_text = short_text.gsub(/\A\s+/,"").gsub(/\n+/,"\n\n")
# Right-strip to end of last paragraph
short_text = short_text[0..short_text.rindex(/\.\n/)]
[title, link, img, short_text, categories]
end | [
"def",
"extract_data",
"item",
",",
"text_limit",
":",
"1200",
"link",
"=",
"item",
".",
"link",
"desc",
"=",
"item",
".",
"description",
"title",
"=",
"item",
".",
"title",
".",
"force_encoding",
"(",
"'UTF-8'",
")",
"case",
"when",
"desc",
".",
"match",
"(",
"/",
"\\|",
"\\|",
"/m",
")",
"img",
",",
"terms",
",",
"text",
"=",
"desc",
".",
"split",
"(",
"'|'",
")",
"when",
"desc",
".",
"include?",
"(",
"'|'",
")",
"img",
",",
"text",
"=",
"desc",
".",
"split",
"(",
"'|'",
")",
"terms",
"=",
"nil",
"when",
"desc",
".",
"match",
"(",
"/",
"\\\"",
"/",
")",
"img",
"=",
"desc",
".",
"match",
"(",
"/",
"\\\"",
"/",
")",
"[",
"1",
"]",
"text",
"=",
"desc",
"terms",
"=",
"nil",
"else",
"img",
",",
"terms",
",",
"text",
"=",
"nil",
",",
"nil",
",",
"desc",
"end",
"categories",
"=",
"if",
"terms",
"terms",
".",
"split",
"(",
"/",
"\\n",
"/",
")",
".",
"select",
"{",
"|",
"g",
"|",
"g",
".",
"match",
"/",
"/",
"}",
".",
"map",
"{",
"|",
"c",
"|",
"c",
".",
"match",
"(",
"/",
"\\n",
"/",
")",
"[",
"1",
"]",
"}",
"else",
"[",
"]",
"end",
"short_text",
"=",
"strip_tags",
"(",
"text",
")",
"[",
"0",
"..",
"text_limit",
"]",
"short_text",
"=",
"short_text",
".",
"gsub",
"(",
"/",
"\\A",
"\\s",
"/",
",",
"\"\"",
")",
".",
"gsub",
"(",
"/",
"\\n",
"/",
",",
"\"\\n\\n\"",
")",
"short_text",
"=",
"short_text",
"[",
"0",
"..",
"short_text",
".",
"rindex",
"(",
"/",
"\\.",
"\\n",
"/",
")",
"]",
"[",
"title",
",",
"link",
",",
"img",
",",
"short_text",
",",
"categories",
"]",
"end"
] | Extract news data from a feed item | [
"Extract",
"news",
"data",
"from",
"a",
"feed",
"item"
] | a5f22f7cb02116ab4dc5b7f2bdb672306b3dac63 | https://github.com/arvicco/poster/blob/a5f22f7cb02116ab4dc5b7f2bdb672306b3dac63/lib/poster/rss.rb#L17-L57 | train |
rnhurt/google_anymote | lib/google_anymote/pair.rb | GoogleAnymote.Pair.start_pairing | def start_pairing
@gtv = GoogleAnymote::TV.new(@cert, host, 9551 + 1)
# Let the TV know that we want to pair with it
send_message(pair, OuterMessage::MessageType::MESSAGE_TYPE_PAIRING_REQUEST)
# Build the options and send them to the TV
options = Options.new
encoding = Options::Encoding.new
encoding.type = Options::Encoding::EncodingType::ENCODING_TYPE_HEXADECIMAL
encoding.symbol_length = 4
options.input_encodings << encoding
options.output_encodings << encoding
send_message(options, OuterMessage::MessageType::MESSAGE_TYPE_OPTIONS)
# Build configuration and send it to the TV
config = Configuration.new
encoding = Options::Encoding.new
encoding.type = Options::Encoding::EncodingType::ENCODING_TYPE_HEXADECIMAL
config.encoding = encoding
config.encoding.symbol_length = 4
config.client_role = Options::RoleType::ROLE_TYPE_INPUT
outer = send_message(config, OuterMessage::MessageType::MESSAGE_TYPE_CONFIGURATION)
raise PairingFailed, outer.status unless OuterMessage::Status::STATUS_OK == outer.status
end | ruby | def start_pairing
@gtv = GoogleAnymote::TV.new(@cert, host, 9551 + 1)
# Let the TV know that we want to pair with it
send_message(pair, OuterMessage::MessageType::MESSAGE_TYPE_PAIRING_REQUEST)
# Build the options and send them to the TV
options = Options.new
encoding = Options::Encoding.new
encoding.type = Options::Encoding::EncodingType::ENCODING_TYPE_HEXADECIMAL
encoding.symbol_length = 4
options.input_encodings << encoding
options.output_encodings << encoding
send_message(options, OuterMessage::MessageType::MESSAGE_TYPE_OPTIONS)
# Build configuration and send it to the TV
config = Configuration.new
encoding = Options::Encoding.new
encoding.type = Options::Encoding::EncodingType::ENCODING_TYPE_HEXADECIMAL
config.encoding = encoding
config.encoding.symbol_length = 4
config.client_role = Options::RoleType::ROLE_TYPE_INPUT
outer = send_message(config, OuterMessage::MessageType::MESSAGE_TYPE_CONFIGURATION)
raise PairingFailed, outer.status unless OuterMessage::Status::STATUS_OK == outer.status
end | [
"def",
"start_pairing",
"@gtv",
"=",
"GoogleAnymote",
"::",
"TV",
".",
"new",
"(",
"@cert",
",",
"host",
",",
"9551",
"+",
"1",
")",
"send_message",
"(",
"pair",
",",
"OuterMessage",
"::",
"MessageType",
"::",
"MESSAGE_TYPE_PAIRING_REQUEST",
")",
"options",
"=",
"Options",
".",
"new",
"encoding",
"=",
"Options",
"::",
"Encoding",
".",
"new",
"encoding",
".",
"type",
"=",
"Options",
"::",
"Encoding",
"::",
"EncodingType",
"::",
"ENCODING_TYPE_HEXADECIMAL",
"encoding",
".",
"symbol_length",
"=",
"4",
"options",
".",
"input_encodings",
"<<",
"encoding",
"options",
".",
"output_encodings",
"<<",
"encoding",
"send_message",
"(",
"options",
",",
"OuterMessage",
"::",
"MessageType",
"::",
"MESSAGE_TYPE_OPTIONS",
")",
"config",
"=",
"Configuration",
".",
"new",
"encoding",
"=",
"Options",
"::",
"Encoding",
".",
"new",
"encoding",
".",
"type",
"=",
"Options",
"::",
"Encoding",
"::",
"EncodingType",
"::",
"ENCODING_TYPE_HEXADECIMAL",
"config",
".",
"encoding",
"=",
"encoding",
"config",
".",
"encoding",
".",
"symbol_length",
"=",
"4",
"config",
".",
"client_role",
"=",
"Options",
"::",
"RoleType",
"::",
"ROLE_TYPE_INPUT",
"outer",
"=",
"send_message",
"(",
"config",
",",
"OuterMessage",
"::",
"MessageType",
"::",
"MESSAGE_TYPE_CONFIGURATION",
")",
"raise",
"PairingFailed",
",",
"outer",
".",
"status",
"unless",
"OuterMessage",
"::",
"Status",
"::",
"STATUS_OK",
"==",
"outer",
".",
"status",
"end"
] | Initializes the Pair class
@param [Object] cert SSL certificate for this client
@param [String] host hostname or IP address of the Google TV
@param [String] client_name name of the client your connecting from
@param [String] service_name name of the service (generally 'AnyMote')
@return an instance of Pair
Start the pairing process
Once the TV recieves the pairing request it will display a 4 digit number.
This number needs to be feed into the next step in the process, complete_pairing(). | [
"Initializes",
"the",
"Pair",
"class"
] | 2992aee3590df9e2cf6d31cebfba2e14be926b8f | https://github.com/rnhurt/google_anymote/blob/2992aee3590df9e2cf6d31cebfba2e14be926b8f/lib/google_anymote/pair.rb#L36-L61 | train |
rnhurt/google_anymote | lib/google_anymote/pair.rb | GoogleAnymote.Pair.complete_pairing | def complete_pairing(code)
# Send secret code to the TV to compete the pairing process
secret = Secret.new
secret.secret = encode_hex_secret(code)
outer = send_message(secret, OuterMessage::MessageType::MESSAGE_TYPE_SECRET)
# Clean up
@gtv.ssl_client.close
raise PairingFailed, outer.status unless OuterMessage::Status::STATUS_OK == outer.status
end | ruby | def complete_pairing(code)
# Send secret code to the TV to compete the pairing process
secret = Secret.new
secret.secret = encode_hex_secret(code)
outer = send_message(secret, OuterMessage::MessageType::MESSAGE_TYPE_SECRET)
# Clean up
@gtv.ssl_client.close
raise PairingFailed, outer.status unless OuterMessage::Status::STATUS_OK == outer.status
end | [
"def",
"complete_pairing",
"(",
"code",
")",
"secret",
"=",
"Secret",
".",
"new",
"secret",
".",
"secret",
"=",
"encode_hex_secret",
"(",
"code",
")",
"outer",
"=",
"send_message",
"(",
"secret",
",",
"OuterMessage",
"::",
"MessageType",
"::",
"MESSAGE_TYPE_SECRET",
")",
"@gtv",
".",
"ssl_client",
".",
"close",
"raise",
"PairingFailed",
",",
"outer",
".",
"status",
"unless",
"OuterMessage",
"::",
"Status",
"::",
"STATUS_OK",
"==",
"outer",
".",
"status",
"end"
] | Complete the pairing process
@param [String] code The code displayed on the Google TV we are trying to pair with. | [
"Complete",
"the",
"pairing",
"process"
] | 2992aee3590df9e2cf6d31cebfba2e14be926b8f | https://github.com/rnhurt/google_anymote/blob/2992aee3590df9e2cf6d31cebfba2e14be926b8f/lib/google_anymote/pair.rb#L67-L77 | train |
rnhurt/google_anymote | lib/google_anymote/pair.rb | GoogleAnymote.Pair.send_message | def send_message(msg, type)
# Build the message and get it's size
message = wrap_message(msg, type).serialize_to_string
message_size = [message.length].pack('N')
# Write the message to the SSL client and get the response
@gtv.ssl_client.write(message_size + message)
data = ""
@gtv.ssl_client.readpartial(1000,data)
@gtv.ssl_client.readpartial(1000,data)
# Extract the response from the Google TV
outer = OuterMessage.new
outer.parse_from_string(data)
return outer
end | ruby | def send_message(msg, type)
# Build the message and get it's size
message = wrap_message(msg, type).serialize_to_string
message_size = [message.length].pack('N')
# Write the message to the SSL client and get the response
@gtv.ssl_client.write(message_size + message)
data = ""
@gtv.ssl_client.readpartial(1000,data)
@gtv.ssl_client.readpartial(1000,data)
# Extract the response from the Google TV
outer = OuterMessage.new
outer.parse_from_string(data)
return outer
end | [
"def",
"send_message",
"(",
"msg",
",",
"type",
")",
"message",
"=",
"wrap_message",
"(",
"msg",
",",
"type",
")",
".",
"serialize_to_string",
"message_size",
"=",
"[",
"message",
".",
"length",
"]",
".",
"pack",
"(",
"'N'",
")",
"@gtv",
".",
"ssl_client",
".",
"write",
"(",
"message_size",
"+",
"message",
")",
"data",
"=",
"\"\"",
"@gtv",
".",
"ssl_client",
".",
"readpartial",
"(",
"1000",
",",
"data",
")",
"@gtv",
".",
"ssl_client",
".",
"readpartial",
"(",
"1000",
",",
"data",
")",
"outer",
"=",
"OuterMessage",
".",
"new",
"outer",
".",
"parse_from_string",
"(",
"data",
")",
"return",
"outer",
"end"
] | Format and send the message to the GoogleTV
@param [String] msg message to send
@param [Object] type type of message to send
@return [Object] the OuterMessage response from the TV | [
"Format",
"and",
"send",
"the",
"message",
"to",
"the",
"GoogleTV"
] | 2992aee3590df9e2cf6d31cebfba2e14be926b8f | https://github.com/rnhurt/google_anymote/blob/2992aee3590df9e2cf6d31cebfba2e14be926b8f/lib/google_anymote/pair.rb#L89-L105 | train |
rnhurt/google_anymote | lib/google_anymote/pair.rb | GoogleAnymote.Pair.wrap_message | def wrap_message(msg, type)
# Wrap it in an envelope
outer = OuterMessage.new
outer.protocol_version = 1
outer.status = OuterMessage::Status::STATUS_OK
outer.type = type
outer.payload = msg.serialize_to_string
return outer
end | ruby | def wrap_message(msg, type)
# Wrap it in an envelope
outer = OuterMessage.new
outer.protocol_version = 1
outer.status = OuterMessage::Status::STATUS_OK
outer.type = type
outer.payload = msg.serialize_to_string
return outer
end | [
"def",
"wrap_message",
"(",
"msg",
",",
"type",
")",
"outer",
"=",
"OuterMessage",
".",
"new",
"outer",
".",
"protocol_version",
"=",
"1",
"outer",
".",
"status",
"=",
"OuterMessage",
"::",
"Status",
"::",
"STATUS_OK",
"outer",
".",
"type",
"=",
"type",
"outer",
".",
"payload",
"=",
"msg",
".",
"serialize_to_string",
"return",
"outer",
"end"
] | Wrap the message in an OuterMessage
@param [String] msg message to send
@param [Object] type type of message to send
@return [Object] a properly formatted OuterMessage | [
"Wrap",
"the",
"message",
"in",
"an",
"OuterMessage"
] | 2992aee3590df9e2cf6d31cebfba2e14be926b8f | https://github.com/rnhurt/google_anymote/blob/2992aee3590df9e2cf6d31cebfba2e14be926b8f/lib/google_anymote/pair.rb#L113-L122 | train |
rnhurt/google_anymote | lib/google_anymote/pair.rb | GoogleAnymote.Pair.encode_hex_secret | def encode_hex_secret secret
# TODO(stevenle): Something further encodes the secret to a 64-char hex
# string. For now, use adb logcat to figure out what the expected challenge
# is. Eventually, make sure the encoding matches the server reference
# implementation:
# http://code.google.com/p/google-tv-pairing-protocol/source/browse/src/com/google/polo/pairing/PoloChallengeResponse.java
encoded_secret = [secret.to_i(16)].pack("N").unpack("cccc")[2..3].pack("c*")
# Per "Polo Implementation Overview", section 6.1, client key material is
# hashed first, followed by the server key material, followed by the nonce.
digest = OpenSSL::Digest::Digest.new('sha256')
digest << @gtv.ssl_client.cert.public_key.n.to_s(2) # client modulus
digest << @gtv.ssl_client.cert.public_key.e.to_s(2) # client exponent
digest << @gtv.ssl_client.peer_cert.public_key.n.to_s(2) # server modulus
digest << @gtv.ssl_client.peer_cert.public_key.e.to_s(2) # server exponent
digest << encoded_secret[encoded_secret.size / 2]
return digest.digest
end | ruby | def encode_hex_secret secret
# TODO(stevenle): Something further encodes the secret to a 64-char hex
# string. For now, use adb logcat to figure out what the expected challenge
# is. Eventually, make sure the encoding matches the server reference
# implementation:
# http://code.google.com/p/google-tv-pairing-protocol/source/browse/src/com/google/polo/pairing/PoloChallengeResponse.java
encoded_secret = [secret.to_i(16)].pack("N").unpack("cccc")[2..3].pack("c*")
# Per "Polo Implementation Overview", section 6.1, client key material is
# hashed first, followed by the server key material, followed by the nonce.
digest = OpenSSL::Digest::Digest.new('sha256')
digest << @gtv.ssl_client.cert.public_key.n.to_s(2) # client modulus
digest << @gtv.ssl_client.cert.public_key.e.to_s(2) # client exponent
digest << @gtv.ssl_client.peer_cert.public_key.n.to_s(2) # server modulus
digest << @gtv.ssl_client.peer_cert.public_key.e.to_s(2) # server exponent
digest << encoded_secret[encoded_secret.size / 2]
return digest.digest
end | [
"def",
"encode_hex_secret",
"secret",
"encoded_secret",
"=",
"[",
"secret",
".",
"to_i",
"(",
"16",
")",
"]",
".",
"pack",
"(",
"\"N\"",
")",
".",
"unpack",
"(",
"\"cccc\"",
")",
"[",
"2",
"..",
"3",
"]",
".",
"pack",
"(",
"\"c*\"",
")",
"digest",
"=",
"OpenSSL",
"::",
"Digest",
"::",
"Digest",
".",
"new",
"(",
"'sha256'",
")",
"digest",
"<<",
"@gtv",
".",
"ssl_client",
".",
"cert",
".",
"public_key",
".",
"n",
".",
"to_s",
"(",
"2",
")",
"digest",
"<<",
"@gtv",
".",
"ssl_client",
".",
"cert",
".",
"public_key",
".",
"e",
".",
"to_s",
"(",
"2",
")",
"digest",
"<<",
"@gtv",
".",
"ssl_client",
".",
"peer_cert",
".",
"public_key",
".",
"n",
".",
"to_s",
"(",
"2",
")",
"digest",
"<<",
"@gtv",
".",
"ssl_client",
".",
"peer_cert",
".",
"public_key",
".",
"e",
".",
"to_s",
"(",
"2",
")",
"digest",
"<<",
"encoded_secret",
"[",
"encoded_secret",
".",
"size",
"/",
"2",
"]",
"return",
"digest",
".",
"digest",
"end"
] | Encode the secret from the TV into an OpenSSL Digest
@param [String] secret pairing code from the TV's screen
@return [Digest] OpenSSL Digest containing the encoded secret | [
"Encode",
"the",
"secret",
"from",
"the",
"TV",
"into",
"an",
"OpenSSL",
"Digest"
] | 2992aee3590df9e2cf6d31cebfba2e14be926b8f | https://github.com/rnhurt/google_anymote/blob/2992aee3590df9e2cf6d31cebfba2e14be926b8f/lib/google_anymote/pair.rb#L129-L148 | train |
robfors/ruby-sumac | lib/sumac/id_allocator.rb | Sumac.IDAllocator.free | def free(id)
enclosing_range_index = @allocated_ranges.index { |range| range.last >= id && range.first <= id }
enclosing_range = @allocated_ranges[enclosing_range_index]
if enclosing_range.size == 1
@allocated_ranges.delete(enclosing_range)
elsif enclosing_range.first == id
@allocated_ranges[enclosing_range_index] = (enclosing_range.first.succ..enclosing_range.last)
elsif enclosing_range.last == id
@allocated_ranges[enclosing_range_index] = (enclosing_range.first..enclosing_range.last.pred)
else
@allocated_ranges[enclosing_range_index] = (enclosing_range.first..id.pred)
@allocated_ranges.insert(enclosing_range_index.succ, (id.succ..enclosing_range.last))
end
end | ruby | def free(id)
enclosing_range_index = @allocated_ranges.index { |range| range.last >= id && range.first <= id }
enclosing_range = @allocated_ranges[enclosing_range_index]
if enclosing_range.size == 1
@allocated_ranges.delete(enclosing_range)
elsif enclosing_range.first == id
@allocated_ranges[enclosing_range_index] = (enclosing_range.first.succ..enclosing_range.last)
elsif enclosing_range.last == id
@allocated_ranges[enclosing_range_index] = (enclosing_range.first..enclosing_range.last.pred)
else
@allocated_ranges[enclosing_range_index] = (enclosing_range.first..id.pred)
@allocated_ranges.insert(enclosing_range_index.succ, (id.succ..enclosing_range.last))
end
end | [
"def",
"free",
"(",
"id",
")",
"enclosing_range_index",
"=",
"@allocated_ranges",
".",
"index",
"{",
"|",
"range",
"|",
"range",
".",
"last",
">=",
"id",
"&&",
"range",
".",
"first",
"<=",
"id",
"}",
"enclosing_range",
"=",
"@allocated_ranges",
"[",
"enclosing_range_index",
"]",
"if",
"enclosing_range",
".",
"size",
"==",
"1",
"@allocated_ranges",
".",
"delete",
"(",
"enclosing_range",
")",
"elsif",
"enclosing_range",
".",
"first",
"==",
"id",
"@allocated_ranges",
"[",
"enclosing_range_index",
"]",
"=",
"(",
"enclosing_range",
".",
"first",
".",
"succ",
"..",
"enclosing_range",
".",
"last",
")",
"elsif",
"enclosing_range",
".",
"last",
"==",
"id",
"@allocated_ranges",
"[",
"enclosing_range_index",
"]",
"=",
"(",
"enclosing_range",
".",
"first",
"..",
"enclosing_range",
".",
"last",
".",
"pred",
")",
"else",
"@allocated_ranges",
"[",
"enclosing_range_index",
"]",
"=",
"(",
"enclosing_range",
".",
"first",
"..",
"id",
".",
"pred",
")",
"@allocated_ranges",
".",
"insert",
"(",
"enclosing_range_index",
".",
"succ",
",",
"(",
"id",
".",
"succ",
"..",
"enclosing_range",
".",
"last",
")",
")",
"end",
"end"
] | Return +id+ back to the allocator so it can be allocated again in the future.
@note trying to free an unallocated id will cause undefined behavior
@return [void] | [
"Return",
"+",
"id",
"+",
"back",
"to",
"the",
"allocator",
"so",
"it",
"can",
"be",
"allocated",
"again",
"in",
"the",
"future",
"."
] | 524fa68b7d1bb10a74baa69cd594ab2b8cae20a3 | https://github.com/robfors/ruby-sumac/blob/524fa68b7d1bb10a74baa69cd594ab2b8cae20a3/lib/sumac/id_allocator.rb#L30-L43 | train |
barkerest/incline | lib/incline/extensions/action_view_base.rb | Incline::Extensions.ActionViewBase.full_title | def full_title(page_title = '')
aname = Rails.application.app_name.strip
return aname if page_title.blank?
"#{page_title.strip} | #{aname}"
end | ruby | def full_title(page_title = '')
aname = Rails.application.app_name.strip
return aname if page_title.blank?
"#{page_title.strip} | #{aname}"
end | [
"def",
"full_title",
"(",
"page_title",
"=",
"''",
")",
"aname",
"=",
"Rails",
".",
"application",
".",
"app_name",
".",
"strip",
"return",
"aname",
"if",
"page_title",
".",
"blank?",
"\"#{page_title.strip} | #{aname}\"",
"end"
] | Gets the full title of the page.
If +page_title+ is left blank, then the +app_name+ attribute of your application is returned.
Otherwise the +app_name+ attribute is appended to the +page_title+ after a pipe symbol.
# app_name = 'My App'
full_title # 'My App'
full_title 'Welcome' # 'Welcome | My App' | [
"Gets",
"the",
"full",
"title",
"of",
"the",
"page",
"."
] | 1ff08db7aa8ab7f86b223268b700bc67d15bb8aa | https://github.com/barkerest/incline/blob/1ff08db7aa8ab7f86b223268b700bc67d15bb8aa/lib/incline/extensions/action_view_base.rb#L24-L28 | train |
barkerest/incline | lib/incline/extensions/action_view_base.rb | Incline::Extensions.ActionViewBase.glyph | def glyph(name, size = '')
size =
case size.to_s.downcase
when 'small', 'sm'
'glyphicon-small'
when 'large', 'lg'
'glyphicon-large'
else
nil
end
name = name.to_s.strip
return nil if name.blank?
result = '<i class="glyphicon glyphicon-' + CGI::escape_html(name)
result += ' ' + size unless size.blank?
result += '"></i>'
result.html_safe
end | ruby | def glyph(name, size = '')
size =
case size.to_s.downcase
when 'small', 'sm'
'glyphicon-small'
when 'large', 'lg'
'glyphicon-large'
else
nil
end
name = name.to_s.strip
return nil if name.blank?
result = '<i class="glyphicon glyphicon-' + CGI::escape_html(name)
result += ' ' + size unless size.blank?
result += '"></i>'
result.html_safe
end | [
"def",
"glyph",
"(",
"name",
",",
"size",
"=",
"''",
")",
"size",
"=",
"case",
"size",
".",
"to_s",
".",
"downcase",
"when",
"'small'",
",",
"'sm'",
"'glyphicon-small'",
"when",
"'large'",
",",
"'lg'",
"'glyphicon-large'",
"else",
"nil",
"end",
"name",
"=",
"name",
".",
"to_s",
".",
"strip",
"return",
"nil",
"if",
"name",
".",
"blank?",
"result",
"=",
"'<i class=\"glyphicon glyphicon-'",
"+",
"CGI",
"::",
"escape_html",
"(",
"name",
")",
"result",
"+=",
"' '",
"+",
"size",
"unless",
"size",
".",
"blank?",
"result",
"+=",
"'\"></i>'",
"result",
".",
"html_safe",
"end"
] | Shows a glyph with an optional size.
The glyph +name+ should be a valid {bootstrap glyph}[http://getbootstrap.com/components/#glyphicons] name.
Strip the prefixed 'glyphicon-' from the name.
The size can be left blank, or set to 'small' or 'large'.
glyph('cloud') # '<i class="glyphicon glyphicon-cloud"></i>' | [
"Shows",
"a",
"glyph",
"with",
"an",
"optional",
"size",
"."
] | 1ff08db7aa8ab7f86b223268b700bc67d15bb8aa | https://github.com/barkerest/incline/blob/1ff08db7aa8ab7f86b223268b700bc67d15bb8aa/lib/incline/extensions/action_view_base.rb#L53-L71 | train |
barkerest/incline | lib/incline/extensions/action_view_base.rb | Incline::Extensions.ActionViewBase.fmt_num | def fmt_num(value, places = 2)
return nil if value.blank?
value =
if value.respond_to?(:to_f)
value.to_f
else
nil
end
return nil unless value.is_a?(::Float)
"%0.#{places}f" % value.round(places)
end | ruby | def fmt_num(value, places = 2)
return nil if value.blank?
value =
if value.respond_to?(:to_f)
value.to_f
else
nil
end
return nil unless value.is_a?(::Float)
"%0.#{places}f" % value.round(places)
end | [
"def",
"fmt_num",
"(",
"value",
",",
"places",
"=",
"2",
")",
"return",
"nil",
"if",
"value",
".",
"blank?",
"value",
"=",
"if",
"value",
".",
"respond_to?",
"(",
":to_f",
")",
"value",
".",
"to_f",
"else",
"nil",
"end",
"return",
"nil",
"unless",
"value",
".",
"is_a?",
"(",
"::",
"Float",
")",
"\"%0.#{places}f\"",
"%",
"value",
".",
"round",
"(",
"places",
")",
"end"
] | Formats a number with the specified number of decimal places.
The +value+ can be any valid numeric expression that can be converted into a float. | [
"Formats",
"a",
"number",
"with",
"the",
"specified",
"number",
"of",
"decimal",
"places",
"."
] | 1ff08db7aa8ab7f86b223268b700bc67d15bb8aa | https://github.com/barkerest/incline/blob/1ff08db7aa8ab7f86b223268b700bc67d15bb8aa/lib/incline/extensions/action_view_base.rb#L299-L312 | train |
barkerest/incline | lib/incline/extensions/action_view_base.rb | Incline::Extensions.ActionViewBase.panel | def panel(title, options = { }, &block)
options = {
type: 'primary',
size: 6,
offset: 3,
open_body: true
}.merge(options || {})
options[:type] = options[:type].to_s.downcase
options[:type] = 'primary' unless %w(primary success info warning danger).include?(options[:type])
options[:size] = 6 unless (1..12).include?(options[:size])
options[:offset] = 3 unless (0..12).include?(options[:offset])
ret = "<div class=\"col-md-#{options[:size]} col-md-offset-#{options[:offset]}\"><div class=\"panel panel-#{options[:type]}\"><div class=\"panel-heading\"><h4 class=\"panel-title\">#{h title}</h4></div>"
ret += '<div class="panel-body">' if options[:open_body]
if block_given?
content = capture { block.call }
content = CGI::escape_html(content) unless content.html_safe?
ret += content
end
ret += '</div>' if options[:open_body]
ret += '</div></div>'
ret.html_safe
end | ruby | def panel(title, options = { }, &block)
options = {
type: 'primary',
size: 6,
offset: 3,
open_body: true
}.merge(options || {})
options[:type] = options[:type].to_s.downcase
options[:type] = 'primary' unless %w(primary success info warning danger).include?(options[:type])
options[:size] = 6 unless (1..12).include?(options[:size])
options[:offset] = 3 unless (0..12).include?(options[:offset])
ret = "<div class=\"col-md-#{options[:size]} col-md-offset-#{options[:offset]}\"><div class=\"panel panel-#{options[:type]}\"><div class=\"panel-heading\"><h4 class=\"panel-title\">#{h title}</h4></div>"
ret += '<div class="panel-body">' if options[:open_body]
if block_given?
content = capture { block.call }
content = CGI::escape_html(content) unless content.html_safe?
ret += content
end
ret += '</div>' if options[:open_body]
ret += '</div></div>'
ret.html_safe
end | [
"def",
"panel",
"(",
"title",
",",
"options",
"=",
"{",
"}",
",",
"&",
"block",
")",
"options",
"=",
"{",
"type",
":",
"'primary'",
",",
"size",
":",
"6",
",",
"offset",
":",
"3",
",",
"open_body",
":",
"true",
"}",
".",
"merge",
"(",
"options",
"||",
"{",
"}",
")",
"options",
"[",
":type",
"]",
"=",
"options",
"[",
":type",
"]",
".",
"to_s",
".",
"downcase",
"options",
"[",
":type",
"]",
"=",
"'primary'",
"unless",
"%w(",
"primary",
"success",
"info",
"warning",
"danger",
")",
".",
"include?",
"(",
"options",
"[",
":type",
"]",
")",
"options",
"[",
":size",
"]",
"=",
"6",
"unless",
"(",
"1",
"..",
"12",
")",
".",
"include?",
"(",
"options",
"[",
":size",
"]",
")",
"options",
"[",
":offset",
"]",
"=",
"3",
"unless",
"(",
"0",
"..",
"12",
")",
".",
"include?",
"(",
"options",
"[",
":offset",
"]",
")",
"ret",
"=",
"\"<div class=\\\"col-md-#{options[:size]} col-md-offset-#{options[:offset]}\\\"><div class=\\\"panel panel-#{options[:type]}\\\"><div class=\\\"panel-heading\\\"><h4 class=\\\"panel-title\\\">#{h title}</h4></div>\"",
"ret",
"+=",
"'<div class=\"panel-body\">'",
"if",
"options",
"[",
":open_body",
"]",
"if",
"block_given?",
"content",
"=",
"capture",
"{",
"block",
".",
"call",
"}",
"content",
"=",
"CGI",
"::",
"escape_html",
"(",
"content",
")",
"unless",
"content",
".",
"html_safe?",
"ret",
"+=",
"content",
"end",
"ret",
"+=",
"'</div>'",
"if",
"options",
"[",
":open_body",
"]",
"ret",
"+=",
"'</div></div>'",
"ret",
".",
"html_safe",
"end"
] | Creates a panel with the specified title.
Valid options:
type::
Type can be :primary, :success, :info, :warning, or :danger. Default value is :primary.
size::
Size can be any value from 1 through 12. Default value is 6.
offset::
Offset can be any value from 1 through 12. Default value is 3.
Common sense is required, for instance you would likely never use an offset of 12, but it is available.
Likewise an offset of 8 with a size of 8 would usually have the same effect as an offset of 12 because
there are only 12 columns to fit your 8 column wide panel in.
open_body::
This can be true or false. Default value is true.
If true, the body division is opened (and closed) by this helper.
If false, then the panel is opened and closed, but the body division is not created.
This allows you to add tables and divisions as you see fit.
Provide a block to render content within the panel. | [
"Creates",
"a",
"panel",
"with",
"the",
"specified",
"title",
"."
] | 1ff08db7aa8ab7f86b223268b700bc67d15bb8aa | https://github.com/barkerest/incline/blob/1ff08db7aa8ab7f86b223268b700bc67d15bb8aa/lib/incline/extensions/action_view_base.rb#L360-L386 | train |
Pistos/m4dbi | lib/m4dbi/model.rb | M4DBI.Model.delete | def delete
if self.class.hooks[:active]
self.class.hooks[:before_delete].each do |block|
self.class.hooks[:active] = false
block.yield self
self.class.hooks[:active] = true
end
end
st = prepare("DELETE FROM #{table} WHERE #{pk_clause}")
num_deleted = st.execute( *pk_values ).affected_count
st.finish
if num_deleted != 1
false
else
if self.class.hooks[:active]
self.class.hooks[:after_delete].each do |block|
self.class.hooks[:active] = false
block.yield self
self.class.hooks[:active] = true
end
end
true
end
end | ruby | def delete
if self.class.hooks[:active]
self.class.hooks[:before_delete].each do |block|
self.class.hooks[:active] = false
block.yield self
self.class.hooks[:active] = true
end
end
st = prepare("DELETE FROM #{table} WHERE #{pk_clause}")
num_deleted = st.execute( *pk_values ).affected_count
st.finish
if num_deleted != 1
false
else
if self.class.hooks[:active]
self.class.hooks[:after_delete].each do |block|
self.class.hooks[:active] = false
block.yield self
self.class.hooks[:active] = true
end
end
true
end
end | [
"def",
"delete",
"if",
"self",
".",
"class",
".",
"hooks",
"[",
":active",
"]",
"self",
".",
"class",
".",
"hooks",
"[",
":before_delete",
"]",
".",
"each",
"do",
"|",
"block",
"|",
"self",
".",
"class",
".",
"hooks",
"[",
":active",
"]",
"=",
"false",
"block",
".",
"yield",
"self",
"self",
".",
"class",
".",
"hooks",
"[",
":active",
"]",
"=",
"true",
"end",
"end",
"st",
"=",
"prepare",
"(",
"\"DELETE FROM #{table} WHERE #{pk_clause}\"",
")",
"num_deleted",
"=",
"st",
".",
"execute",
"(",
"*",
"pk_values",
")",
".",
"affected_count",
"st",
".",
"finish",
"if",
"num_deleted",
"!=",
"1",
"false",
"else",
"if",
"self",
".",
"class",
".",
"hooks",
"[",
":active",
"]",
"self",
".",
"class",
".",
"hooks",
"[",
":after_delete",
"]",
".",
"each",
"do",
"|",
"block",
"|",
"self",
".",
"class",
".",
"hooks",
"[",
":active",
"]",
"=",
"false",
"block",
".",
"yield",
"self",
"self",
".",
"class",
".",
"hooks",
"[",
":active",
"]",
"=",
"true",
"end",
"end",
"true",
"end",
"end"
] | Returns true iff the record and only the record was successfully deleted. | [
"Returns",
"true",
"iff",
"the",
"record",
"and",
"only",
"the",
"record",
"was",
"successfully",
"deleted",
"."
] | 603d7fefb621fe34a940fa8e8b798ee581823cb3 | https://github.com/Pistos/m4dbi/blob/603d7fefb621fe34a940fa8e8b798ee581823cb3/lib/m4dbi/model.rb#L456-L480 | train |
HParker/sock-drawer | lib/sock/server.rb | Sock.Server.subscribe | def subscribe(subscription)
@logger.info "Subscribing to: #{subscription + '*'}"
pubsub.psubscribe(subscription + '*') do |chan, msg|
@logger.info "pushing c: #{chan} msg: #{msg}"
channel(chan).push(msg)
end
end | ruby | def subscribe(subscription)
@logger.info "Subscribing to: #{subscription + '*'}"
pubsub.psubscribe(subscription + '*') do |chan, msg|
@logger.info "pushing c: #{chan} msg: #{msg}"
channel(chan).push(msg)
end
end | [
"def",
"subscribe",
"(",
"subscription",
")",
"@logger",
".",
"info",
"\"Subscribing to: #{subscription + '*'}\"",
"pubsub",
".",
"psubscribe",
"(",
"subscription",
"+",
"'*'",
")",
"do",
"|",
"chan",
",",
"msg",
"|",
"@logger",
".",
"info",
"\"pushing c: #{chan} msg: #{msg}\"",
"channel",
"(",
"chan",
")",
".",
"push",
"(",
"msg",
")",
"end",
"end"
] | subscribe fires a event on a EM channel whenever a message is fired on a pattern matching `name`.
@name (default: "sock-hook/") + '*' | [
"subscribe",
"fires",
"a",
"event",
"on",
"a",
"EM",
"channel",
"whenever",
"a",
"message",
"is",
"fired",
"on",
"a",
"pattern",
"matching",
"name",
"."
] | 87fffa745cedc3adbeec41a3afdd19a3fae92ab2 | https://github.com/HParker/sock-drawer/blob/87fffa745cedc3adbeec41a3afdd19a3fae92ab2/lib/sock/server.rb#L31-L37 | train |
LiveTyping/live-front-rails | lib/live-front/tab_helper.rb | LiveFront.TabHelper.nav_link | def nav_link(options = {}, &block)
c, a = fetch_controller_and_action(options)
p = options.delete(:params) || {}
klass = page_active?(c, a, p) ? 'active' : ''
# Add our custom class into the html_options, which may or may not exist
# and which may or may not already have a :class key
o = options.delete(:html_options) || {}
o[:class] = "#{o[:class]} #{klass}".strip
if block_given?
content_tag(:li, capture(&block), o)
else
content_tag(:li, nil, o)
end
end | ruby | def nav_link(options = {}, &block)
c, a = fetch_controller_and_action(options)
p = options.delete(:params) || {}
klass = page_active?(c, a, p) ? 'active' : ''
# Add our custom class into the html_options, which may or may not exist
# and which may or may not already have a :class key
o = options.delete(:html_options) || {}
o[:class] = "#{o[:class]} #{klass}".strip
if block_given?
content_tag(:li, capture(&block), o)
else
content_tag(:li, nil, o)
end
end | [
"def",
"nav_link",
"(",
"options",
"=",
"{",
"}",
",",
"&",
"block",
")",
"c",
",",
"a",
"=",
"fetch_controller_and_action",
"(",
"options",
")",
"p",
"=",
"options",
".",
"delete",
"(",
":params",
")",
"||",
"{",
"}",
"klass",
"=",
"page_active?",
"(",
"c",
",",
"a",
",",
"p",
")",
"?",
"'active'",
":",
"''",
"o",
"=",
"options",
".",
"delete",
"(",
":html_options",
")",
"||",
"{",
"}",
"o",
"[",
":class",
"]",
"=",
"\"#{o[:class]} #{klass}\"",
".",
"strip",
"if",
"block_given?",
"content_tag",
"(",
":li",
",",
"capture",
"(",
"&",
"block",
")",
",",
"o",
")",
"else",
"content_tag",
"(",
":li",
",",
"nil",
",",
"o",
")",
"end",
"end"
] | Navigation link helper
Returns an `li` element with an 'active' class if the supplied
controller(s) and/or action(s) are currently active. The content of the
element is the value passed to the block.
options - The options hash used to determine if the element is "active" (default: {})
:controller - One or more controller names to check (optional).
:action - One or more action names to check (optional).
:path - A shorthand path, such as 'dashboard#index', to check (optional).
:html_options - Extra options to be passed to the list element (optional).
block - An optional block that will become the contents of the returned
`li` element.
When both :controller and :action are specified, BOTH must match in order
to be marked as active. When only one is given, either can match.
Examples
# Assuming we're on TreeController#show
# Controller matches, but action doesn't
nav_link(controller: [:tree, :refs], action: :edit) { "Hello" }
# => '<li>Hello</li>'
# Controller matches
nav_link(controller: [:tree, :refs]) { "Hello" }
# => '<li class="active">Hello</li>'
# Shorthand path
nav_link(path: 'tree#show') { "Hello" }
# => '<li class="active">Hello</li>'
# Supplying custom options for the list element
nav_link(controller: :tree, html_options: {class: 'home'}) { "Hello" }
# => '<li class="home active">Hello</li>'
Returns a list item element String | [
"Navigation",
"link",
"helper"
] | 605946ec748bab2a2a751fd7eebcbf9a0e99832c | https://github.com/LiveTyping/live-front-rails/blob/605946ec748bab2a2a751fd7eebcbf9a0e99832c/lib/live-front/tab_helper.rb#L43-L60 | train |
JoshMcKin/hot_tub | lib/hot_tub/sessions.rb | HotTub.Sessions.get_or_set | def get_or_set(key, pool_options={}, &client_block)
unless @_staged[key]
@mutex.synchronize do
@_staged[key] ||= [pool_options,client_block]
end
end
get(key)
end | ruby | def get_or_set(key, pool_options={}, &client_block)
unless @_staged[key]
@mutex.synchronize do
@_staged[key] ||= [pool_options,client_block]
end
end
get(key)
end | [
"def",
"get_or_set",
"(",
"key",
",",
"pool_options",
"=",
"{",
"}",
",",
"&",
"client_block",
")",
"unless",
"@_staged",
"[",
"key",
"]",
"@mutex",
".",
"synchronize",
"do",
"@_staged",
"[",
"key",
"]",
"||=",
"[",
"pool_options",
",",
"client_block",
"]",
"end",
"end",
"get",
"(",
"key",
")",
"end"
] | Adds session unless it already exists and returns
the session | [
"Adds",
"session",
"unless",
"it",
"already",
"exists",
"and",
"returns",
"the",
"session"
] | 44f22b0dfbca40bfe7cc4f7e6393122c88d7da0d | https://github.com/JoshMcKin/hot_tub/blob/44f22b0dfbca40bfe7cc4f7e6393122c88d7da0d/lib/hot_tub/sessions.rb#L133-L140 | train |
JoshMcKin/hot_tub | lib/hot_tub/sessions.rb | HotTub.Sessions.delete | def delete(key)
deleted = false
pool = nil
@mutex.synchronize do
pool = @_sessions.delete(key)
end
if pool
pool.shutdown!
deleted = true
HotTub.logger.info "[HotTub] #{key} was deleted from #{@name}." if HotTub.logger
end
deleted
end | ruby | def delete(key)
deleted = false
pool = nil
@mutex.synchronize do
pool = @_sessions.delete(key)
end
if pool
pool.shutdown!
deleted = true
HotTub.logger.info "[HotTub] #{key} was deleted from #{@name}." if HotTub.logger
end
deleted
end | [
"def",
"delete",
"(",
"key",
")",
"deleted",
"=",
"false",
"pool",
"=",
"nil",
"@mutex",
".",
"synchronize",
"do",
"pool",
"=",
"@_sessions",
".",
"delete",
"(",
"key",
")",
"end",
"if",
"pool",
"pool",
".",
"shutdown!",
"deleted",
"=",
"true",
"HotTub",
".",
"logger",
".",
"info",
"\"[HotTub] #{key} was deleted from #{@name}.\"",
"if",
"HotTub",
".",
"logger",
"end",
"deleted",
"end"
] | Deletes and shutdowns the pool if its found. | [
"Deletes",
"and",
"shutdowns",
"the",
"pool",
"if",
"its",
"found",
"."
] | 44f22b0dfbca40bfe7cc4f7e6393122c88d7da0d | https://github.com/JoshMcKin/hot_tub/blob/44f22b0dfbca40bfe7cc4f7e6393122c88d7da0d/lib/hot_tub/sessions.rb#L144-L156 | train |
JoshMcKin/hot_tub | lib/hot_tub/sessions.rb | HotTub.Sessions.reap! | def reap!
HotTub.logger.info "[HotTub] Reaping #{@name}!" if HotTub.log_trace?
@mutex.synchronize do
@_sessions.each_value do |pool|
break if @shutdown
pool.reap!
end
end
nil
end | ruby | def reap!
HotTub.logger.info "[HotTub] Reaping #{@name}!" if HotTub.log_trace?
@mutex.synchronize do
@_sessions.each_value do |pool|
break if @shutdown
pool.reap!
end
end
nil
end | [
"def",
"reap!",
"HotTub",
".",
"logger",
".",
"info",
"\"[HotTub] Reaping #{@name}!\"",
"if",
"HotTub",
".",
"log_trace?",
"@mutex",
".",
"synchronize",
"do",
"@_sessions",
".",
"each_value",
"do",
"|",
"pool",
"|",
"break",
"if",
"@shutdown",
"pool",
".",
"reap!",
"end",
"end",
"nil",
"end"
] | Remove and close extra clients | [
"Remove",
"and",
"close",
"extra",
"clients"
] | 44f22b0dfbca40bfe7cc4f7e6393122c88d7da0d | https://github.com/JoshMcKin/hot_tub/blob/44f22b0dfbca40bfe7cc4f7e6393122c88d7da0d/lib/hot_tub/sessions.rb#L221-L230 | train |
anga/BetterRailsDebugger | lib/better_rails_debugger/parser/ruby/processor.rb | BetterRailsDebugger::Parser::Ruby.Processor.emit_signal | def emit_signal(signal_name, node)
@subscriptions ||= Hash.new()
@runner ||= BetterRailsDebugger::Parser::Ruby::ContextRunner.new self
(@subscriptions[signal_name] || {}).values.each do |block|
@runner.node = node
@runner.instance_eval &block
# block.call(node)
end
end | ruby | def emit_signal(signal_name, node)
@subscriptions ||= Hash.new()
@runner ||= BetterRailsDebugger::Parser::Ruby::ContextRunner.new self
(@subscriptions[signal_name] || {}).values.each do |block|
@runner.node = node
@runner.instance_eval &block
# block.call(node)
end
end | [
"def",
"emit_signal",
"(",
"signal_name",
",",
"node",
")",
"@subscriptions",
"||=",
"Hash",
".",
"new",
"(",
")",
"@runner",
"||=",
"BetterRailsDebugger",
"::",
"Parser",
"::",
"Ruby",
"::",
"ContextRunner",
".",
"new",
"self",
"(",
"@subscriptions",
"[",
"signal_name",
"]",
"||",
"{",
"}",
")",
".",
"values",
".",
"each",
"do",
"|",
"block",
"|",
"@runner",
".",
"node",
"=",
"node",
"@runner",
".",
"instance_eval",
"&",
"block",
"end",
"end"
] | Call all subscriptions for the given signal
@param signal_name Symbol
@param args Hash | [
"Call",
"all",
"subscriptions",
"for",
"the",
"given",
"signal"
] | 2ac7af13b8ee12483bd9a92680d8f43042f1f1d5 | https://github.com/anga/BetterRailsDebugger/blob/2ac7af13b8ee12483bd9a92680d8f43042f1f1d5/lib/better_rails_debugger/parser/ruby/processor.rb#L10-L18 | train |
anga/BetterRailsDebugger | lib/better_rails_debugger/parser/ruby/processor.rb | BetterRailsDebugger::Parser::Ruby.Processor.subscribe_signal | def subscribe_signal(signal_name, step=:first_pass, &block)
key = SecureRandom.hex(5)
@subscriptions ||= Hash.new()
@subscriptions[signal_name] ||= Hash.new
@subscriptions[signal_name][key] = block
key
end | ruby | def subscribe_signal(signal_name, step=:first_pass, &block)
key = SecureRandom.hex(5)
@subscriptions ||= Hash.new()
@subscriptions[signal_name] ||= Hash.new
@subscriptions[signal_name][key] = block
key
end | [
"def",
"subscribe_signal",
"(",
"signal_name",
",",
"step",
"=",
":first_pass",
",",
"&",
"block",
")",
"key",
"=",
"SecureRandom",
".",
"hex",
"(",
"5",
")",
"@subscriptions",
"||=",
"Hash",
".",
"new",
"(",
")",
"@subscriptions",
"[",
"signal_name",
"]",
"||=",
"Hash",
".",
"new",
"@subscriptions",
"[",
"signal_name",
"]",
"[",
"key",
"]",
"=",
"block",
"key",
"end"
] | Subscribe to a particular signal
@param signal_name Symbol
@param step Symbol May be :first_pass or :second_pass
@param block Proc | [
"Subscribe",
"to",
"a",
"particular",
"signal"
] | 2ac7af13b8ee12483bd9a92680d8f43042f1f1d5 | https://github.com/anga/BetterRailsDebugger/blob/2ac7af13b8ee12483bd9a92680d8f43042f1f1d5/lib/better_rails_debugger/parser/ruby/processor.rb#L24-L30 | train |
tbpgr/sublime_sunippetter | lib/sublime_sunippetter_dsl.rb | SublimeSunippetter.Dsl.add | def add(method_name, *args)
return if error?(method_name, *args)
has_do_block = args.include?('block@d')
has_brace_block = args.include?('block@b')
args = delete_block_args args
@target_methods << TargetMethod.new do |t|
t.method_name = method_name
t.args = args
t.has_do_block = has_do_block
t.has_brace_block = has_brace_block
end
end | ruby | def add(method_name, *args)
return if error?(method_name, *args)
has_do_block = args.include?('block@d')
has_brace_block = args.include?('block@b')
args = delete_block_args args
@target_methods << TargetMethod.new do |t|
t.method_name = method_name
t.args = args
t.has_do_block = has_do_block
t.has_brace_block = has_brace_block
end
end | [
"def",
"add",
"(",
"method_name",
",",
"*",
"args",
")",
"return",
"if",
"error?",
"(",
"method_name",
",",
"*",
"args",
")",
"has_do_block",
"=",
"args",
".",
"include?",
"(",
"'block@d'",
")",
"has_brace_block",
"=",
"args",
".",
"include?",
"(",
"'block@b'",
")",
"args",
"=",
"delete_block_args",
"args",
"@target_methods",
"<<",
"TargetMethod",
".",
"new",
"do",
"|",
"t",
"|",
"t",
".",
"method_name",
"=",
"method_name",
"t",
".",
"args",
"=",
"args",
"t",
".",
"has_do_block",
"=",
"has_do_block",
"t",
".",
"has_brace_block",
"=",
"has_brace_block",
"end",
"end"
] | init default values
add sunippet information | [
"init",
"default",
"values",
"add",
"sunippet",
"information"
] | a731a8a52fe457d742e78f50a4009b5b01f0640d | https://github.com/tbpgr/sublime_sunippetter/blob/a731a8a52fe457d742e78f50a4009b5b01f0640d/lib/sublime_sunippetter_dsl.rb#L18-L29 | train |
flyingmachine/whoops_logger | lib/whoops_logger/sender.rb | WhoopsLogger.Sender.send_message | def send_message(data)
# TODO: format
# TODO: validation
data = prepare_data(data)
logger.debug { "Sending request to #{url.to_s}:\n#{data}" } if logger
http =
Net::HTTP::Proxy(proxy_host, proxy_port, proxy_user, proxy_pass).
new(url.host, url.port)
http.read_timeout = http_read_timeout
http.open_timeout = http_open_timeout
http.use_ssl = secure
response = begin
http.post(url.path, data, HEADERS)
rescue *HTTP_ERRORS => e
log :error, "Timeout while contacting the Whoops server."
nil
end
case response
when Net::HTTPSuccess then
log :info, "Success: #{response.class}", response
else
log :error, "Failure: #{response.class}", response
end
if response && response.respond_to?(:body)
error_id = response.body.match(%r{<error-id[^>]*>(.*?)</error-id>})
error_id[1] if error_id
end
end | ruby | def send_message(data)
# TODO: format
# TODO: validation
data = prepare_data(data)
logger.debug { "Sending request to #{url.to_s}:\n#{data}" } if logger
http =
Net::HTTP::Proxy(proxy_host, proxy_port, proxy_user, proxy_pass).
new(url.host, url.port)
http.read_timeout = http_read_timeout
http.open_timeout = http_open_timeout
http.use_ssl = secure
response = begin
http.post(url.path, data, HEADERS)
rescue *HTTP_ERRORS => e
log :error, "Timeout while contacting the Whoops server."
nil
end
case response
when Net::HTTPSuccess then
log :info, "Success: #{response.class}", response
else
log :error, "Failure: #{response.class}", response
end
if response && response.respond_to?(:body)
error_id = response.body.match(%r{<error-id[^>]*>(.*?)</error-id>})
error_id[1] if error_id
end
end | [
"def",
"send_message",
"(",
"data",
")",
"data",
"=",
"prepare_data",
"(",
"data",
")",
"logger",
".",
"debug",
"{",
"\"Sending request to #{url.to_s}:\\n#{data}\"",
"}",
"if",
"logger",
"http",
"=",
"Net",
"::",
"HTTP",
"::",
"Proxy",
"(",
"proxy_host",
",",
"proxy_port",
",",
"proxy_user",
",",
"proxy_pass",
")",
".",
"new",
"(",
"url",
".",
"host",
",",
"url",
".",
"port",
")",
"http",
".",
"read_timeout",
"=",
"http_read_timeout",
"http",
".",
"open_timeout",
"=",
"http_open_timeout",
"http",
".",
"use_ssl",
"=",
"secure",
"response",
"=",
"begin",
"http",
".",
"post",
"(",
"url",
".",
"path",
",",
"data",
",",
"HEADERS",
")",
"rescue",
"*",
"HTTP_ERRORS",
"=>",
"e",
"log",
":error",
",",
"\"Timeout while contacting the Whoops server.\"",
"nil",
"end",
"case",
"response",
"when",
"Net",
"::",
"HTTPSuccess",
"then",
"log",
":info",
",",
"\"Success: #{response.class}\"",
",",
"response",
"else",
"log",
":error",
",",
"\"Failure: #{response.class}\"",
",",
"response",
"end",
"if",
"response",
"&&",
"response",
".",
"respond_to?",
"(",
":body",
")",
"error_id",
"=",
"response",
".",
"body",
".",
"match",
"(",
"%r{",
"}",
")",
"error_id",
"[",
"1",
"]",
"if",
"error_id",
"end",
"end"
] | Sends the notice data off to Whoops for processing.
@param [Hash] data The notice to be sent off | [
"Sends",
"the",
"notice",
"data",
"off",
"to",
"Whoops",
"for",
"processing",
"."
] | e1db5362b67c58f60018c9e0d653094fbe286014 | https://github.com/flyingmachine/whoops_logger/blob/e1db5362b67c58f60018c9e0d653094fbe286014/lib/whoops_logger/sender.rb#L28-L60 | train |
ffmike/shoehorn | lib/shoehorn/documents_base.rb | Shoehorn.DocumentsBase.status | def status(inserter_id)
status_hash = Hash.new
xml = Builder::XmlMarkup.new
xml.instruct!
xml.Request(:xmlns => "urn:sbx:apis:SbxBaseComponents") do |xml|
connection.requester_credentials_block(xml)
xml.GetDocumentStatusCall do |xml|
xml.InserterId(inserter_id)
end
end
response = connection.post_xml(xml)
document = REXML::Document.new(response)
status_hash[:status] = document.elements["GetDocumentStatusCallResponse"].elements["Status"].text
status_hash[:document_id] = document.elements["GetDocumentStatusCallResponse"].elements["DocumentId"].text
status_hash[:document_type] = document.elements["GetDocumentStatusCallResponse"].elements["DocumentType"].text
status_hash
end | ruby | def status(inserter_id)
status_hash = Hash.new
xml = Builder::XmlMarkup.new
xml.instruct!
xml.Request(:xmlns => "urn:sbx:apis:SbxBaseComponents") do |xml|
connection.requester_credentials_block(xml)
xml.GetDocumentStatusCall do |xml|
xml.InserterId(inserter_id)
end
end
response = connection.post_xml(xml)
document = REXML::Document.new(response)
status_hash[:status] = document.elements["GetDocumentStatusCallResponse"].elements["Status"].text
status_hash[:document_id] = document.elements["GetDocumentStatusCallResponse"].elements["DocumentId"].text
status_hash[:document_type] = document.elements["GetDocumentStatusCallResponse"].elements["DocumentType"].text
status_hash
end | [
"def",
"status",
"(",
"inserter_id",
")",
"status_hash",
"=",
"Hash",
".",
"new",
"xml",
"=",
"Builder",
"::",
"XmlMarkup",
".",
"new",
"xml",
".",
"instruct!",
"xml",
".",
"Request",
"(",
":xmlns",
"=>",
"\"urn:sbx:apis:SbxBaseComponents\"",
")",
"do",
"|",
"xml",
"|",
"connection",
".",
"requester_credentials_block",
"(",
"xml",
")",
"xml",
".",
"GetDocumentStatusCall",
"do",
"|",
"xml",
"|",
"xml",
".",
"InserterId",
"(",
"inserter_id",
")",
"end",
"end",
"response",
"=",
"connection",
".",
"post_xml",
"(",
"xml",
")",
"document",
"=",
"REXML",
"::",
"Document",
".",
"new",
"(",
"response",
")",
"status_hash",
"[",
":status",
"]",
"=",
"document",
".",
"elements",
"[",
"\"GetDocumentStatusCallResponse\"",
"]",
".",
"elements",
"[",
"\"Status\"",
"]",
".",
"text",
"status_hash",
"[",
":document_id",
"]",
"=",
"document",
".",
"elements",
"[",
"\"GetDocumentStatusCallResponse\"",
"]",
".",
"elements",
"[",
"\"DocumentId\"",
"]",
".",
"text",
"status_hash",
"[",
":document_type",
"]",
"=",
"document",
".",
"elements",
"[",
"\"GetDocumentStatusCallResponse\"",
"]",
".",
"elements",
"[",
"\"DocumentType\"",
"]",
".",
"text",
"status_hash",
"end"
] | Requires an inserter id from an upload call | [
"Requires",
"an",
"inserter",
"id",
"from",
"an",
"upload",
"call"
] | b3da6d2bc4bd49652ac76197d01077b14bafb70a | https://github.com/ffmike/shoehorn/blob/b3da6d2bc4bd49652ac76197d01077b14bafb70a/lib/shoehorn/documents_base.rb#L68-L84 | train |
DigitPaint/html_mockup | lib/html_mockup/release/processors/requirejs.rb | HtmlMockup::Release::Processors.Requirejs.rjs_check | def rjs_check(path = @options[:rjs])
rjs_command = rjs_file(path) || rjs_bin(path)
if !(rjs_command)
raise RuntimeError, "Could not find r.js optimizer in #{path.inspect} - try updating this by npm install -g requirejs"
end
rjs_command
end | ruby | def rjs_check(path = @options[:rjs])
rjs_command = rjs_file(path) || rjs_bin(path)
if !(rjs_command)
raise RuntimeError, "Could not find r.js optimizer in #{path.inspect} - try updating this by npm install -g requirejs"
end
rjs_command
end | [
"def",
"rjs_check",
"(",
"path",
"=",
"@options",
"[",
":rjs",
"]",
")",
"rjs_command",
"=",
"rjs_file",
"(",
"path",
")",
"||",
"rjs_bin",
"(",
"path",
")",
"if",
"!",
"(",
"rjs_command",
")",
"raise",
"RuntimeError",
",",
"\"Could not find r.js optimizer in #{path.inspect} - try updating this by npm install -g requirejs\"",
"end",
"rjs_command",
"end"
] | Incase both a file and bin version are availble file version is taken
@return rjs_command to invoke r.js optimizer with | [
"Incase",
"both",
"a",
"file",
"and",
"bin",
"version",
"are",
"availble",
"file",
"version",
"is",
"taken"
] | 976edadc01216b82a8cea177f53fb32559eaf41e | https://github.com/DigitPaint/html_mockup/blob/976edadc01216b82a8cea177f53fb32559eaf41e/lib/html_mockup/release/processors/requirejs.rb#L88-L94 | train |
martinpoljak/types | lib/types.rb | Types.Type.match_type? | def match_type?(object)
result = object.kind_of_any? self.type_classes
if not result
result = object.type_of_any? self.type_types
end
return result
end | ruby | def match_type?(object)
result = object.kind_of_any? self.type_classes
if not result
result = object.type_of_any? self.type_types
end
return result
end | [
"def",
"match_type?",
"(",
"object",
")",
"result",
"=",
"object",
".",
"kind_of_any?",
"self",
".",
"type_classes",
"if",
"not",
"result",
"result",
"=",
"object",
".",
"type_of_any?",
"self",
".",
"type_types",
"end",
"return",
"result",
"end"
] | Matches object is of this type.
@param [Object] object object for type matching
@return [Boolean] +true+ if match, +false+ in otherwise | [
"Matches",
"object",
"is",
"of",
"this",
"type",
"."
] | 7742b90580a375de71b25344369bb76283962798 | https://github.com/martinpoljak/types/blob/7742b90580a375de71b25344369bb76283962798/lib/types.rb#L47-L54 | train |
doubleleft/hook-ruby | lib/hook-client/collection.rb | Hook.Collection.create | def create data
if data.kind_of?(Array)
# TODO: server should accept multiple items to create,
# instead of making multiple requests.
data.map {|item| self.create(item) }
else
@client.post @segments, data
end
end | ruby | def create data
if data.kind_of?(Array)
# TODO: server should accept multiple items to create,
# instead of making multiple requests.
data.map {|item| self.create(item) }
else
@client.post @segments, data
end
end | [
"def",
"create",
"data",
"if",
"data",
".",
"kind_of?",
"(",
"Array",
")",
"data",
".",
"map",
"{",
"|",
"item",
"|",
"self",
".",
"create",
"(",
"item",
")",
"}",
"else",
"@client",
".",
"post",
"@segments",
",",
"data",
"end",
"end"
] | Create an item into the collection
@param data [Hash, Array] item or array of items
@return [Hash, Array] | [
"Create",
"an",
"item",
"into",
"the",
"collection"
] | f6acdd89dfe6ed9161380300c2dff2f19f0f744a | https://github.com/doubleleft/hook-ruby/blob/f6acdd89dfe6ed9161380300c2dff2f19f0f744a/lib/hook-client/collection.rb#L35-L43 | train |
doubleleft/hook-ruby | lib/hook-client/collection.rb | Hook.Collection.where | def where fields = {}, operation = 'and'
fields.each_pair do |k, value|
field = (k.respond_to?(:field) ? k.field : k).to_s
comparation = k.respond_to?(:comparation) ? k.comparation : '='
# Range syntatic sugar
value = [ value.first, value.last ] if value.kind_of?(Range)
@wheres << [field, comparation, value, operation]
end
self
end | ruby | def where fields = {}, operation = 'and'
fields.each_pair do |k, value|
field = (k.respond_to?(:field) ? k.field : k).to_s
comparation = k.respond_to?(:comparation) ? k.comparation : '='
# Range syntatic sugar
value = [ value.first, value.last ] if value.kind_of?(Range)
@wheres << [field, comparation, value, operation]
end
self
end | [
"def",
"where",
"fields",
"=",
"{",
"}",
",",
"operation",
"=",
"'and'",
"fields",
".",
"each_pair",
"do",
"|",
"k",
",",
"value",
"|",
"field",
"=",
"(",
"k",
".",
"respond_to?",
"(",
":field",
")",
"?",
"k",
".",
"field",
":",
"k",
")",
".",
"to_s",
"comparation",
"=",
"k",
".",
"respond_to?",
"(",
":comparation",
")",
"?",
"k",
".",
"comparation",
":",
"'='",
"value",
"=",
"[",
"value",
".",
"first",
",",
"value",
".",
"last",
"]",
"if",
"value",
".",
"kind_of?",
"(",
"Range",
")",
"@wheres",
"<<",
"[",
"field",
",",
"comparation",
",",
"value",
",",
"operation",
"]",
"end",
"self",
"end"
] | Add where clause to the current query.
Supported modifiers on fields: .gt, .gte, .lt, .lte, .ne, .in, .not_in, .nin, .like, .between, .not_between
@param fields [Hash] fields and values to filter
@param [String] operation (and, or)
@example
hook.collection(:movies).where({
:name => "Hook",
:year.gt => 1990
})
@example Using Range
hook.collection(:movies).where({
:name.like => "%panic%",
:year.between => 1990..2014
})
@return [Collection] self | [
"Add",
"where",
"clause",
"to",
"the",
"current",
"query",
"."
] | f6acdd89dfe6ed9161380300c2dff2f19f0f744a | https://github.com/doubleleft/hook-ruby/blob/f6acdd89dfe6ed9161380300c2dff2f19f0f744a/lib/hook-client/collection.rb#L92-L103 | train |
doubleleft/hook-ruby | lib/hook-client/collection.rb | Hook.Collection.order | def order fields
by_num = { 1 => 'asc', -1 => 'desc' }
ordering = []
fields.each_pair do |key, value|
ordering << [key.to_s, by_num[value] || value]
end
@ordering = ordering
self
end | ruby | def order fields
by_num = { 1 => 'asc', -1 => 'desc' }
ordering = []
fields.each_pair do |key, value|
ordering << [key.to_s, by_num[value] || value]
end
@ordering = ordering
self
end | [
"def",
"order",
"fields",
"by_num",
"=",
"{",
"1",
"=>",
"'asc'",
",",
"-",
"1",
"=>",
"'desc'",
"}",
"ordering",
"=",
"[",
"]",
"fields",
".",
"each_pair",
"do",
"|",
"key",
",",
"value",
"|",
"ordering",
"<<",
"[",
"key",
".",
"to_s",
",",
"by_num",
"[",
"value",
"]",
"||",
"value",
"]",
"end",
"@ordering",
"=",
"ordering",
"self",
"end"
] | Add order clause to the query.
@param fields [String] ...
@return [Collection] self | [
"Add",
"order",
"clause",
"to",
"the",
"query",
"."
] | f6acdd89dfe6ed9161380300c2dff2f19f0f744a | https://github.com/doubleleft/hook-ruby/blob/f6acdd89dfe6ed9161380300c2dff2f19f0f744a/lib/hook-client/collection.rb#L116-L124 | train |
qwertos/URIx-Util | lib/urix/urix.rb | URIx.URIx.claim_interface | def claim_interface
devices = usb.devices(:idVendor => VENDOR_ID, :idProduct => PRODUCT_ID)
unless devices.first then
return
end
@device = devices.first
@handle = @device.open
@handle.detach_kernel_driver(HID_INTERFACE)
@handle.claim_interface( HID_INTERFACE )
end | ruby | def claim_interface
devices = usb.devices(:idVendor => VENDOR_ID, :idProduct => PRODUCT_ID)
unless devices.first then
return
end
@device = devices.first
@handle = @device.open
@handle.detach_kernel_driver(HID_INTERFACE)
@handle.claim_interface( HID_INTERFACE )
end | [
"def",
"claim_interface",
"devices",
"=",
"usb",
".",
"devices",
"(",
":idVendor",
"=>",
"VENDOR_ID",
",",
":idProduct",
"=>",
"PRODUCT_ID",
")",
"unless",
"devices",
".",
"first",
"then",
"return",
"end",
"@device",
"=",
"devices",
".",
"first",
"@handle",
"=",
"@device",
".",
"open",
"@handle",
".",
"detach_kernel_driver",
"(",
"HID_INTERFACE",
")",
"@handle",
".",
"claim_interface",
"(",
"HID_INTERFACE",
")",
"end"
] | Creates a new URIx interface.
Claim the USB interface for this program. Must be
called to begin using the interface. | [
"Creates",
"a",
"new",
"URIx",
"interface",
".",
"Claim",
"the",
"USB",
"interface",
"for",
"this",
"program",
".",
"Must",
"be",
"called",
"to",
"begin",
"using",
"the",
"interface",
"."
] | a7b565543aad947ccdb3ffb869e98401b8efb798 | https://github.com/qwertos/URIx-Util/blob/a7b565543aad947ccdb3ffb869e98401b8efb798/lib/urix/urix.rb#L26-L38 | train |
qwertos/URIx-Util | lib/urix/urix.rb | URIx.URIx.set_output | def set_output pin, state
state = false if state == :low
state = true if state == :high
if ( @pin_states >> ( pin - 1 )).odd? && ( state == false ) or
( @pin_states >> ( pin - 1 )).even? && ( state == true ) then
mask = 0 + ( 1 << ( pin - 1 ))
@pin_states ^= mask
end
write_output
end | ruby | def set_output pin, state
state = false if state == :low
state = true if state == :high
if ( @pin_states >> ( pin - 1 )).odd? && ( state == false ) or
( @pin_states >> ( pin - 1 )).even? && ( state == true ) then
mask = 0 + ( 1 << ( pin - 1 ))
@pin_states ^= mask
end
write_output
end | [
"def",
"set_output",
"pin",
",",
"state",
"state",
"=",
"false",
"if",
"state",
"==",
":low",
"state",
"=",
"true",
"if",
"state",
"==",
":high",
"if",
"(",
"@pin_states",
">>",
"(",
"pin",
"-",
"1",
")",
")",
".",
"odd?",
"&&",
"(",
"state",
"==",
"false",
")",
"or",
"(",
"@pin_states",
">>",
"(",
"pin",
"-",
"1",
")",
")",
".",
"even?",
"&&",
"(",
"state",
"==",
"true",
")",
"then",
"mask",
"=",
"0",
"+",
"(",
"1",
"<<",
"(",
"pin",
"-",
"1",
")",
")",
"@pin_states",
"^=",
"mask",
"end",
"write_output",
"end"
] | Sets the state of a GPIO pin.
@param pin [Integer] ID of GPIO pin.
@param state [Boolean] State to set pin to. True == :high | [
"Sets",
"the",
"state",
"of",
"a",
"GPIO",
"pin",
"."
] | a7b565543aad947ccdb3ffb869e98401b8efb798 | https://github.com/qwertos/URIx-Util/blob/a7b565543aad947ccdb3ffb869e98401b8efb798/lib/urix/urix.rb#L54-L66 | train |
qwertos/URIx-Util | lib/urix/urix.rb | URIx.URIx.set_pin_mode | def set_pin_mode pin, mode
if ( @pin_modes >> ( pin - 1 )).odd? && ( mode == :input ) or
( @pin_modes >> ( pin - 1 )).even? && ( mode == :output ) then
mask = 0 + ( 1 << ( pin - 1 ))
@pin_modes ^= mask
end
end | ruby | def set_pin_mode pin, mode
if ( @pin_modes >> ( pin - 1 )).odd? && ( mode == :input ) or
( @pin_modes >> ( pin - 1 )).even? && ( mode == :output ) then
mask = 0 + ( 1 << ( pin - 1 ))
@pin_modes ^= mask
end
end | [
"def",
"set_pin_mode",
"pin",
",",
"mode",
"if",
"(",
"@pin_modes",
">>",
"(",
"pin",
"-",
"1",
")",
")",
".",
"odd?",
"&&",
"(",
"mode",
"==",
":input",
")",
"or",
"(",
"@pin_modes",
">>",
"(",
"pin",
"-",
"1",
")",
")",
".",
"even?",
"&&",
"(",
"mode",
"==",
":output",
")",
"then",
"mask",
"=",
"0",
"+",
"(",
"1",
"<<",
"(",
"pin",
"-",
"1",
")",
")",
"@pin_modes",
"^=",
"mask",
"end",
"end"
] | Sets the mode of a GPIO pin to input or output.
@param pin [Integer] ID of GPIO pin.
@param mode [Symbol] :input or :output | [
"Sets",
"the",
"mode",
"of",
"a",
"GPIO",
"pin",
"to",
"input",
"or",
"output",
"."
] | a7b565543aad947ccdb3ffb869e98401b8efb798 | https://github.com/qwertos/URIx-Util/blob/a7b565543aad947ccdb3ffb869e98401b8efb798/lib/urix/urix.rb#L73-L80 | train |
Montage-Inc/ruby-montage | lib/montage/client.rb | Montage.Client.auth | def auth
build_response("token") do
connection.post do |req|
req.headers.delete("Authorization")
req.url "auth/"
req.body = { username: username, password: password }.to_json
end
end
end | ruby | def auth
build_response("token") do
connection.post do |req|
req.headers.delete("Authorization")
req.url "auth/"
req.body = { username: username, password: password }.to_json
end
end
end | [
"def",
"auth",
"build_response",
"(",
"\"token\"",
")",
"do",
"connection",
".",
"post",
"do",
"|",
"req",
"|",
"req",
".",
"headers",
".",
"delete",
"(",
"\"Authorization\"",
")",
"req",
".",
"url",
"\"auth/\"",
"req",
".",
"body",
"=",
"{",
"username",
":",
"username",
",",
"password",
":",
"password",
"}",
".",
"to_json",
"end",
"end",
"end"
] | Attempts to authenticate with the Montage API
* *Returns* :
- A hash containing a valid token or an error string, oh no! | [
"Attempts",
"to",
"authenticate",
"with",
"the",
"Montage",
"API"
] | 2e6f7e591f2f87158994c17ad9619fa29b716bad | https://github.com/Montage-Inc/ruby-montage/blob/2e6f7e591f2f87158994c17ad9619fa29b716bad/lib/montage/client.rb#L88-L96 | train |
Montage-Inc/ruby-montage | lib/montage/client.rb | Montage.Client.build_response | def build_response(resource_name)
response = yield
resource = response_successful?(response) ? resource_name : "error"
response_object = Montage::Response.new(response.status, response.body, resource)
set_token(response_object.token.value) if resource_name == "token" && response.success?
response_object
end | ruby | def build_response(resource_name)
response = yield
resource = response_successful?(response) ? resource_name : "error"
response_object = Montage::Response.new(response.status, response.body, resource)
set_token(response_object.token.value) if resource_name == "token" && response.success?
response_object
end | [
"def",
"build_response",
"(",
"resource_name",
")",
"response",
"=",
"yield",
"resource",
"=",
"response_successful?",
"(",
"response",
")",
"?",
"resource_name",
":",
"\"error\"",
"response_object",
"=",
"Montage",
"::",
"Response",
".",
"new",
"(",
"response",
".",
"status",
",",
"response",
".",
"body",
",",
"resource",
")",
"set_token",
"(",
"response_object",
".",
"token",
".",
"value",
")",
"if",
"resource_name",
"==",
"\"token\"",
"&&",
"response",
".",
"success?",
"response_object",
"end"
] | Instantiates a response object based on the yielded block
* *Args* :
- +resource_name+ -> The name of the Montage resource
* *Returns* :
* A Montage::Response Object containing:
- A http status code
- The response body
- The resource name | [
"Instantiates",
"a",
"response",
"object",
"based",
"on",
"the",
"yielded",
"block"
] | 2e6f7e591f2f87158994c17ad9619fa29b716bad | https://github.com/Montage-Inc/ruby-montage/blob/2e6f7e591f2f87158994c17ad9619fa29b716bad/lib/montage/client.rb#L214-L223 | train |
Montage-Inc/ruby-montage | lib/montage/client.rb | Montage.Client.connection | def connection
@connect ||= Faraday.new do |f|
f.adapter :net_http
f.headers = connection_headers
f.url_prefix = "#{default_url_prefix}/api/v#{api_version}/"
f.response :json, content_type: /\bjson$/
end
end | ruby | def connection
@connect ||= Faraday.new do |f|
f.adapter :net_http
f.headers = connection_headers
f.url_prefix = "#{default_url_prefix}/api/v#{api_version}/"
f.response :json, content_type: /\bjson$/
end
end | [
"def",
"connection",
"@connect",
"||=",
"Faraday",
".",
"new",
"do",
"|",
"f",
"|",
"f",
".",
"adapter",
":net_http",
"f",
".",
"headers",
"=",
"connection_headers",
"f",
".",
"url_prefix",
"=",
"\"#{default_url_prefix}/api/v#{api_version}/\"",
"f",
".",
"response",
":json",
",",
"content_type",
":",
"/",
"\\b",
"/",
"end",
"end"
] | Creates an Faraday connection instance for requests
* *Returns* :
- A Faraday connection object with an instance specific configuration | [
"Creates",
"an",
"Faraday",
"connection",
"instance",
"for",
"requests"
] | 2e6f7e591f2f87158994c17ad9619fa29b716bad | https://github.com/Montage-Inc/ruby-montage/blob/2e6f7e591f2f87158994c17ad9619fa29b716bad/lib/montage/client.rb#L245-L252 | train |
jimmyz/ruby-fs-stack | lib/ruby-fs-stack/familytree/communicator.rb | FamilytreeV2.Communicator.write_note | def write_note(options)
url = "#{Base}note"
note = Org::Familysearch::Ws::Familytree::V2::Schema::Note.new
note.build(options)
familytree = Org::Familysearch::Ws::Familytree::V2::Schema::FamilyTree.new
familytree.notes = [note]
res = @fs_communicator.post(url,familytree.to_json)
familytree = Org::Familysearch::Ws::Familytree::V2::Schema::FamilyTree.from_json JSON.parse(res.body)
return familytree.notes.first
end | ruby | def write_note(options)
url = "#{Base}note"
note = Org::Familysearch::Ws::Familytree::V2::Schema::Note.new
note.build(options)
familytree = Org::Familysearch::Ws::Familytree::V2::Schema::FamilyTree.new
familytree.notes = [note]
res = @fs_communicator.post(url,familytree.to_json)
familytree = Org::Familysearch::Ws::Familytree::V2::Schema::FamilyTree.from_json JSON.parse(res.body)
return familytree.notes.first
end | [
"def",
"write_note",
"(",
"options",
")",
"url",
"=",
"\"#{Base}note\"",
"note",
"=",
"Org",
"::",
"Familysearch",
"::",
"Ws",
"::",
"Familytree",
"::",
"V2",
"::",
"Schema",
"::",
"Note",
".",
"new",
"note",
".",
"build",
"(",
"options",
")",
"familytree",
"=",
"Org",
"::",
"Familysearch",
"::",
"Ws",
"::",
"Familytree",
"::",
"V2",
"::",
"Schema",
"::",
"FamilyTree",
".",
"new",
"familytree",
".",
"notes",
"=",
"[",
"note",
"]",
"res",
"=",
"@fs_communicator",
".",
"post",
"(",
"url",
",",
"familytree",
".",
"to_json",
")",
"familytree",
"=",
"Org",
"::",
"Familysearch",
"::",
"Ws",
"::",
"Familytree",
"::",
"V2",
"::",
"Schema",
"::",
"FamilyTree",
".",
"from_json",
"JSON",
".",
"parse",
"(",
"res",
".",
"body",
")",
"return",
"familytree",
".",
"notes",
".",
"first",
"end"
] | Writes a note attached to the value ID of the specific person or relationship.
====Params
* <tt>options</tt> - Options for the note including the following:
* <tt>:personId</tt> - the person ID if attaching to a person assertion.
* <tt>:spouseIds</tt> - an Array of spouse IDs if creating a note attached to a spouse
relationship assertion.
* <tt>:parentIds</tt> - an Array of parent IDs if creating a note attached to a parent
relationship assertion. If creating a note for a child-parent or parent-child
relationship, you will need only one parent ID in the array along with a :childId option.
* <tt>:childId</tt> - a child ID.
* <tt>:text</tt> - the text of the note (required).
* <tt>:assertionId</tt> - the valueId of the assertion you are attaching this note to. | [
"Writes",
"a",
"note",
"attached",
"to",
"the",
"value",
"ID",
"of",
"the",
"specific",
"person",
"or",
"relationship",
"."
] | 11281818635984971026e750d32a5c4599557dd1 | https://github.com/jimmyz/ruby-fs-stack/blob/11281818635984971026e750d32a5c4599557dd1/lib/ruby-fs-stack/familytree/communicator.rb#L233-L242 | train |
jimmyz/ruby-fs-stack | lib/ruby-fs-stack/familytree/communicator.rb | FamilytreeV2.Communicator.combine | def combine(person_array)
url = Base + 'person'
version_persons = self.person person_array, :genders => 'none', :events => 'none', :names => 'none'
combine_person = Org::Familysearch::Ws::Familytree::V2::Schema::Person.new
combine_person.create_combine(version_persons)
familytree = Org::Familysearch::Ws::Familytree::V2::Schema::FamilyTree.new
familytree.persons = [combine_person]
res = @fs_communicator.post(url,familytree.to_json)
familytree = Org::Familysearch::Ws::Familytree::V2::Schema::FamilyTree.from_json JSON.parse(res.body)
return familytree.persons[0]
end | ruby | def combine(person_array)
url = Base + 'person'
version_persons = self.person person_array, :genders => 'none', :events => 'none', :names => 'none'
combine_person = Org::Familysearch::Ws::Familytree::V2::Schema::Person.new
combine_person.create_combine(version_persons)
familytree = Org::Familysearch::Ws::Familytree::V2::Schema::FamilyTree.new
familytree.persons = [combine_person]
res = @fs_communicator.post(url,familytree.to_json)
familytree = Org::Familysearch::Ws::Familytree::V2::Schema::FamilyTree.from_json JSON.parse(res.body)
return familytree.persons[0]
end | [
"def",
"combine",
"(",
"person_array",
")",
"url",
"=",
"Base",
"+",
"'person'",
"version_persons",
"=",
"self",
".",
"person",
"person_array",
",",
":genders",
"=>",
"'none'",
",",
":events",
"=>",
"'none'",
",",
":names",
"=>",
"'none'",
"combine_person",
"=",
"Org",
"::",
"Familysearch",
"::",
"Ws",
"::",
"Familytree",
"::",
"V2",
"::",
"Schema",
"::",
"Person",
".",
"new",
"combine_person",
".",
"create_combine",
"(",
"version_persons",
")",
"familytree",
"=",
"Org",
"::",
"Familysearch",
"::",
"Ws",
"::",
"Familytree",
"::",
"V2",
"::",
"Schema",
"::",
"FamilyTree",
".",
"new",
"familytree",
".",
"persons",
"=",
"[",
"combine_person",
"]",
"res",
"=",
"@fs_communicator",
".",
"post",
"(",
"url",
",",
"familytree",
".",
"to_json",
")",
"familytree",
"=",
"Org",
"::",
"Familysearch",
"::",
"Ws",
"::",
"Familytree",
"::",
"V2",
"::",
"Schema",
"::",
"FamilyTree",
".",
"from_json",
"JSON",
".",
"parse",
"(",
"res",
".",
"body",
")",
"return",
"familytree",
".",
"persons",
"[",
"0",
"]",
"end"
] | Combines person into a new person
====Params
* <tt>person_array</tt> - an array of person IDs. | [
"Combines",
"person",
"into",
"a",
"new",
"person"
] | 11281818635984971026e750d32a5c4599557dd1 | https://github.com/jimmyz/ruby-fs-stack/blob/11281818635984971026e750d32a5c4599557dd1/lib/ruby-fs-stack/familytree/communicator.rb#L248-L258 | train |
mrsimonfletcher/roroacms | app/controllers/roroacms/admin/comments_controller.rb | Roroacms.Admin::CommentsController.edit | def edit
# add breadcrumb and set title
add_breadcrumb I18n.t("controllers.admin.comments.edit.breadcrumb")
set_title(I18n.t("controllers.admin.comments.edit.title"))
@comment = Comment.find(params[:id])
end | ruby | def edit
# add breadcrumb and set title
add_breadcrumb I18n.t("controllers.admin.comments.edit.breadcrumb")
set_title(I18n.t("controllers.admin.comments.edit.title"))
@comment = Comment.find(params[:id])
end | [
"def",
"edit",
"add_breadcrumb",
"I18n",
".",
"t",
"(",
"\"controllers.admin.comments.edit.breadcrumb\"",
")",
"set_title",
"(",
"I18n",
".",
"t",
"(",
"\"controllers.admin.comments.edit.title\"",
")",
")",
"@comment",
"=",
"Comment",
".",
"find",
"(",
"params",
"[",
":id",
"]",
")",
"end"
] | get and disply certain comment | [
"get",
"and",
"disply",
"certain",
"comment"
] | 62654a2f2a48e3adb3105f4dafb6e315b460eaf4 | https://github.com/mrsimonfletcher/roroacms/blob/62654a2f2a48e3adb3105f4dafb6e315b460eaf4/app/controllers/roroacms/admin/comments_controller.rb#L15-L21 | train |
mrsimonfletcher/roroacms | app/controllers/roroacms/admin/comments_controller.rb | Roroacms.Admin::CommentsController.update | def update
@comment = Comment.find(params[:id])
atts = comments_params
respond_to do |format|
if @comment.update_attributes(atts)
format.html { redirect_to edit_admin_comment_path(@comment), notice: I18n.t("controllers.admin.comments.update.flash.success") }
else
format.html {
# add breadcrumb and set title
add_breadcrumb I18n.t("controllers.admin.comments.edit.breadcrumb")
render action: "edit"
}
end
end
end | ruby | def update
@comment = Comment.find(params[:id])
atts = comments_params
respond_to do |format|
if @comment.update_attributes(atts)
format.html { redirect_to edit_admin_comment_path(@comment), notice: I18n.t("controllers.admin.comments.update.flash.success") }
else
format.html {
# add breadcrumb and set title
add_breadcrumb I18n.t("controllers.admin.comments.edit.breadcrumb")
render action: "edit"
}
end
end
end | [
"def",
"update",
"@comment",
"=",
"Comment",
".",
"find",
"(",
"params",
"[",
":id",
"]",
")",
"atts",
"=",
"comments_params",
"respond_to",
"do",
"|",
"format",
"|",
"if",
"@comment",
".",
"update_attributes",
"(",
"atts",
")",
"format",
".",
"html",
"{",
"redirect_to",
"edit_admin_comment_path",
"(",
"@comment",
")",
",",
"notice",
":",
"I18n",
".",
"t",
"(",
"\"controllers.admin.comments.update.flash.success\"",
")",
"}",
"else",
"format",
".",
"html",
"{",
"add_breadcrumb",
"I18n",
".",
"t",
"(",
"\"controllers.admin.comments.edit.breadcrumb\"",
")",
"render",
"action",
":",
"\"edit\"",
"}",
"end",
"end",
"end"
] | update the comment. You are able to update everything about the comment as an admin | [
"update",
"the",
"comment",
".",
"You",
"are",
"able",
"to",
"update",
"everything",
"about",
"the",
"comment",
"as",
"an",
"admin"
] | 62654a2f2a48e3adb3105f4dafb6e315b460eaf4 | https://github.com/mrsimonfletcher/roroacms/blob/62654a2f2a48e3adb3105f4dafb6e315b460eaf4/app/controllers/roroacms/admin/comments_controller.rb#L26-L43 | train |
mrsimonfletcher/roroacms | app/controllers/roroacms/admin/comments_controller.rb | Roroacms.Admin::CommentsController.destroy | def destroy
@comment = Comment.find(params[:id])
@comment.destroy
respond_to do |format|
format.html { redirect_to admin_comments_path, notice: I18n.t("controllers.admin.comments.destroy.flash.success") }
end
end | ruby | def destroy
@comment = Comment.find(params[:id])
@comment.destroy
respond_to do |format|
format.html { redirect_to admin_comments_path, notice: I18n.t("controllers.admin.comments.destroy.flash.success") }
end
end | [
"def",
"destroy",
"@comment",
"=",
"Comment",
".",
"find",
"(",
"params",
"[",
":id",
"]",
")",
"@comment",
".",
"destroy",
"respond_to",
"do",
"|",
"format",
"|",
"format",
".",
"html",
"{",
"redirect_to",
"admin_comments_path",
",",
"notice",
":",
"I18n",
".",
"t",
"(",
"\"controllers.admin.comments.destroy.flash.success\"",
")",
"}",
"end",
"end"
] | delete the comment | [
"delete",
"the",
"comment"
] | 62654a2f2a48e3adb3105f4dafb6e315b460eaf4 | https://github.com/mrsimonfletcher/roroacms/blob/62654a2f2a48e3adb3105f4dafb6e315b460eaf4/app/controllers/roroacms/admin/comments_controller.rb#L48-L57 | train |
mrsimonfletcher/roroacms | app/controllers/roroacms/admin/comments_controller.rb | Roroacms.Admin::CommentsController.bulk_update | def bulk_update
# This is what makes the update
func = Comment.bulk_update params
respond_to do |format|
format.html { redirect_to admin_comments_path, notice: func == 'ntd' ? I18n.t("controllers.admin.comments.bulk_update.flash.nothing_to_do") : I18n.t("controllers.admin.comments.bulk_update.flash.success", func: func) }
end
end | ruby | def bulk_update
# This is what makes the update
func = Comment.bulk_update params
respond_to do |format|
format.html { redirect_to admin_comments_path, notice: func == 'ntd' ? I18n.t("controllers.admin.comments.bulk_update.flash.nothing_to_do") : I18n.t("controllers.admin.comments.bulk_update.flash.success", func: func) }
end
end | [
"def",
"bulk_update",
"func",
"=",
"Comment",
".",
"bulk_update",
"params",
"respond_to",
"do",
"|",
"format",
"|",
"format",
".",
"html",
"{",
"redirect_to",
"admin_comments_path",
",",
"notice",
":",
"func",
"==",
"'ntd'",
"?",
"I18n",
".",
"t",
"(",
"\"controllers.admin.comments.bulk_update.flash.nothing_to_do\"",
")",
":",
"I18n",
".",
"t",
"(",
"\"controllers.admin.comments.bulk_update.flash.success\"",
",",
"func",
":",
"func",
")",
"}",
"end",
"end"
] | bulk_update function takes all of the checked options and updates them with the given option selected. The options for the bulk update in comments area are
- Unapprove
- Approve
- Mark as Spam
- Destroy | [
"bulk_update",
"function",
"takes",
"all",
"of",
"the",
"checked",
"options",
"and",
"updates",
"them",
"with",
"the",
"given",
"option",
"selected",
".",
"The",
"options",
"for",
"the",
"bulk",
"update",
"in",
"comments",
"area",
"are",
"-",
"Unapprove",
"-",
"Approve",
"-",
"Mark",
"as",
"Spam",
"-",
"Destroy"
] | 62654a2f2a48e3adb3105f4dafb6e315b460eaf4 | https://github.com/mrsimonfletcher/roroacms/blob/62654a2f2a48e3adb3105f4dafb6e315b460eaf4/app/controllers/roroacms/admin/comments_controller.rb#L66-L74 | train |
mrsimonfletcher/roroacms | app/controllers/roroacms/admin/comments_controller.rb | Roroacms.Admin::CommentsController.mark_as_spam | def mark_as_spam
comment = Comment.find(params[:id])
comment.comment_approved = "S"
comment.is_spam = "S"
respond_to do |format|
if comment.save
format.html { redirect_to admin_comments_path, notice: I18n.t("controllers.admin.comments.mark_as_spam.flash.success") }
else
format.html { render action: "index" }
end
end
end | ruby | def mark_as_spam
comment = Comment.find(params[:id])
comment.comment_approved = "S"
comment.is_spam = "S"
respond_to do |format|
if comment.save
format.html { redirect_to admin_comments_path, notice: I18n.t("controllers.admin.comments.mark_as_spam.flash.success") }
else
format.html { render action: "index" }
end
end
end | [
"def",
"mark_as_spam",
"comment",
"=",
"Comment",
".",
"find",
"(",
"params",
"[",
":id",
"]",
")",
"comment",
".",
"comment_approved",
"=",
"\"S\"",
"comment",
".",
"is_spam",
"=",
"\"S\"",
"respond_to",
"do",
"|",
"format",
"|",
"if",
"comment",
".",
"save",
"format",
".",
"html",
"{",
"redirect_to",
"admin_comments_path",
",",
"notice",
":",
"I18n",
".",
"t",
"(",
"\"controllers.admin.comments.mark_as_spam.flash.success\"",
")",
"}",
"else",
"format",
".",
"html",
"{",
"render",
"action",
":",
"\"index\"",
"}",
"end",
"end",
"end"
] | mark_as_spam function is a button on the ui and so need its own function. The function simply marks the comment as spam against the record in the database.
the record is then not visable unless you explicity tell the system that you want to see spam records. | [
"mark_as_spam",
"function",
"is",
"a",
"button",
"on",
"the",
"ui",
"and",
"so",
"need",
"its",
"own",
"function",
".",
"The",
"function",
"simply",
"marks",
"the",
"comment",
"as",
"spam",
"against",
"the",
"record",
"in",
"the",
"database",
".",
"the",
"record",
"is",
"then",
"not",
"visable",
"unless",
"you",
"explicity",
"tell",
"the",
"system",
"that",
"you",
"want",
"to",
"see",
"spam",
"records",
"."
] | 62654a2f2a48e3adb3105f4dafb6e315b460eaf4 | https://github.com/mrsimonfletcher/roroacms/blob/62654a2f2a48e3adb3105f4dafb6e315b460eaf4/app/controllers/roroacms/admin/comments_controller.rb#L80-L91 | train |
Dev-Crea/swagger-docs-generator | lib/swagger_docs_generator/metadata/sort.rb | SwaggerDocsGenerator.Sort.sort_by_tag | def sort_by_tag
by_tag = Hash[@routes[:paths].sort_by do |_key, value|
value.first[1]['tags']
end]
place_readme_first(by_tag)
end | ruby | def sort_by_tag
by_tag = Hash[@routes[:paths].sort_by do |_key, value|
value.first[1]['tags']
end]
place_readme_first(by_tag)
end | [
"def",
"sort_by_tag",
"by_tag",
"=",
"Hash",
"[",
"@routes",
"[",
":paths",
"]",
".",
"sort_by",
"do",
"|",
"_key",
",",
"value",
"|",
"value",
".",
"first",
"[",
"1",
"]",
"[",
"'tags'",
"]",
"end",
"]",
"place_readme_first",
"(",
"by_tag",
")",
"end"
] | Sort routes by tags | [
"Sort",
"routes",
"by",
"tags"
] | 5d3de176aa1119cb38100b451bee028d66c0809d | https://github.com/Dev-Crea/swagger-docs-generator/blob/5d3de176aa1119cb38100b451bee028d66c0809d/lib/swagger_docs_generator/metadata/sort.rb#L20-L25 | train |
whistler/active-tracker | lib/active_tracker/tracker.rb | ActiveTracker.Tracker.method_missing | def method_missing(m, *args, &block)
if @tracker_names.include? m
@tracker_blocks[m] = block
else
super(name, *args, &block)
end
end | ruby | def method_missing(m, *args, &block)
if @tracker_names.include? m
@tracker_blocks[m] = block
else
super(name, *args, &block)
end
end | [
"def",
"method_missing",
"(",
"m",
",",
"*",
"args",
",",
"&",
"block",
")",
"if",
"@tracker_names",
".",
"include?",
"m",
"@tracker_blocks",
"[",
"m",
"]",
"=",
"block",
"else",
"super",
"(",
"name",
",",
"*",
"args",
",",
"&",
"block",
")",
"end",
"end"
] | store tracker code blocks | [
"store",
"tracker",
"code",
"blocks"
] | 5a618042f3f7f9425e31dc083b7b9b970cbcf0b9 | https://github.com/whistler/active-tracker/blob/5a618042f3f7f9425e31dc083b7b9b970cbcf0b9/lib/active_tracker/tracker.rb#L34-L40 | train |
jgoizueta/numerals | lib/numerals/rounding.rb | Numerals.Rounding.truncate | def truncate(numeral, round_up=nil)
check_base numeral
unless simplifying? # TODO: could simplify this just skiping on free?
n = precision(numeral)
if n == 0
return numeral if numeral.repeating? # or rails inexact...
n = numeral.digits.size
end
unless n >= numeral.digits.size && numeral.approximate?
if n < numeral.digits.size - 1
rest_digits = numeral.digits[n+1..-1]
else
rest_digits = []
end
if numeral.repeating? && numeral.repeat < numeral.digits.size && n >= numeral.repeat
rest_digits += numeral.digits[numeral.repeat..-1]
end
digits = numeral.digits[0, n]
if digits.size < n
digits += (digits.size...n).map{|i| numeral.digit_value_at(i)}
end
if numeral.base % 2 == 0
tie_digit = numeral.base / 2
max_lo = tie_digit - 1
else
max_lo = numeral.base / 2
end
next_digit = numeral.digit_value_at(n)
if next_digit == 0
unless round_up.nil? && rest_digits.all?{|d| d == 0}
round_up = :lo
end
elsif next_digit <= max_lo # next_digit < tie_digit
round_up = :lo
elsif next_digit == tie_digit
if round_up || rest_digits.any?{|d| d != 0}
round_up = :hi
else
round_up = :tie
end
else # next_digit > tie_digit
round_up = :hi
end
numeral = Numeral[
digits, point: numeral.point, sign: numeral.sign,
base: numeral.base,
normalize: :approximate
]
end
end
[numeral, round_up]
end | ruby | def truncate(numeral, round_up=nil)
check_base numeral
unless simplifying? # TODO: could simplify this just skiping on free?
n = precision(numeral)
if n == 0
return numeral if numeral.repeating? # or rails inexact...
n = numeral.digits.size
end
unless n >= numeral.digits.size && numeral.approximate?
if n < numeral.digits.size - 1
rest_digits = numeral.digits[n+1..-1]
else
rest_digits = []
end
if numeral.repeating? && numeral.repeat < numeral.digits.size && n >= numeral.repeat
rest_digits += numeral.digits[numeral.repeat..-1]
end
digits = numeral.digits[0, n]
if digits.size < n
digits += (digits.size...n).map{|i| numeral.digit_value_at(i)}
end
if numeral.base % 2 == 0
tie_digit = numeral.base / 2
max_lo = tie_digit - 1
else
max_lo = numeral.base / 2
end
next_digit = numeral.digit_value_at(n)
if next_digit == 0
unless round_up.nil? && rest_digits.all?{|d| d == 0}
round_up = :lo
end
elsif next_digit <= max_lo # next_digit < tie_digit
round_up = :lo
elsif next_digit == tie_digit
if round_up || rest_digits.any?{|d| d != 0}
round_up = :hi
else
round_up = :tie
end
else # next_digit > tie_digit
round_up = :hi
end
numeral = Numeral[
digits, point: numeral.point, sign: numeral.sign,
base: numeral.base,
normalize: :approximate
]
end
end
[numeral, round_up]
end | [
"def",
"truncate",
"(",
"numeral",
",",
"round_up",
"=",
"nil",
")",
"check_base",
"numeral",
"unless",
"simplifying?",
"n",
"=",
"precision",
"(",
"numeral",
")",
"if",
"n",
"==",
"0",
"return",
"numeral",
"if",
"numeral",
".",
"repeating?",
"n",
"=",
"numeral",
".",
"digits",
".",
"size",
"end",
"unless",
"n",
">=",
"numeral",
".",
"digits",
".",
"size",
"&&",
"numeral",
".",
"approximate?",
"if",
"n",
"<",
"numeral",
".",
"digits",
".",
"size",
"-",
"1",
"rest_digits",
"=",
"numeral",
".",
"digits",
"[",
"n",
"+",
"1",
"..",
"-",
"1",
"]",
"else",
"rest_digits",
"=",
"[",
"]",
"end",
"if",
"numeral",
".",
"repeating?",
"&&",
"numeral",
".",
"repeat",
"<",
"numeral",
".",
"digits",
".",
"size",
"&&",
"n",
">=",
"numeral",
".",
"repeat",
"rest_digits",
"+=",
"numeral",
".",
"digits",
"[",
"numeral",
".",
"repeat",
"..",
"-",
"1",
"]",
"end",
"digits",
"=",
"numeral",
".",
"digits",
"[",
"0",
",",
"n",
"]",
"if",
"digits",
".",
"size",
"<",
"n",
"digits",
"+=",
"(",
"digits",
".",
"size",
"...",
"n",
")",
".",
"map",
"{",
"|",
"i",
"|",
"numeral",
".",
"digit_value_at",
"(",
"i",
")",
"}",
"end",
"if",
"numeral",
".",
"base",
"%",
"2",
"==",
"0",
"tie_digit",
"=",
"numeral",
".",
"base",
"/",
"2",
"max_lo",
"=",
"tie_digit",
"-",
"1",
"else",
"max_lo",
"=",
"numeral",
".",
"base",
"/",
"2",
"end",
"next_digit",
"=",
"numeral",
".",
"digit_value_at",
"(",
"n",
")",
"if",
"next_digit",
"==",
"0",
"unless",
"round_up",
".",
"nil?",
"&&",
"rest_digits",
".",
"all?",
"{",
"|",
"d",
"|",
"d",
"==",
"0",
"}",
"round_up",
"=",
":lo",
"end",
"elsif",
"next_digit",
"<=",
"max_lo",
"round_up",
"=",
":lo",
"elsif",
"next_digit",
"==",
"tie_digit",
"if",
"round_up",
"||",
"rest_digits",
".",
"any?",
"{",
"|",
"d",
"|",
"d",
"!=",
"0",
"}",
"round_up",
"=",
":hi",
"else",
"round_up",
"=",
":tie",
"end",
"else",
"round_up",
"=",
":hi",
"end",
"numeral",
"=",
"Numeral",
"[",
"digits",
",",
"point",
":",
"numeral",
".",
"point",
",",
"sign",
":",
"numeral",
".",
"sign",
",",
"base",
":",
"numeral",
".",
"base",
",",
"normalize",
":",
":approximate",
"]",
"end",
"end",
"[",
"numeral",
",",
"round_up",
"]",
"end"
] | Truncate a numeral and return also a round_up value with information about
the digits beyond the truncation point that can be used to round the truncated
numeral. If the numeral has already been truncated, the round_up result of
that prior truncation should be passed as the second argument. | [
"Truncate",
"a",
"numeral",
"and",
"return",
"also",
"a",
"round_up",
"value",
"with",
"information",
"about",
"the",
"digits",
"beyond",
"the",
"truncation",
"point",
"that",
"can",
"be",
"used",
"to",
"round",
"the",
"truncated",
"numeral",
".",
"If",
"the",
"numeral",
"has",
"already",
"been",
"truncated",
"the",
"round_up",
"result",
"of",
"that",
"prior",
"truncation",
"should",
"be",
"passed",
"as",
"the",
"second",
"argument",
"."
] | a195e75f689af926537f791441bf8d11590c99c0 | https://github.com/jgoizueta/numerals/blob/a195e75f689af926537f791441bf8d11590c99c0/lib/numerals/rounding.rb#L239-L290 | train |
jgoizueta/numerals | lib/numerals/rounding.rb | Numerals.Rounding.adjust | def adjust(numeral, round_up)
check_base numeral
point, digits = Flt::Support.adjust_digits(
numeral.point, numeral.digits.digits_array,
round_mode: @mode,
negative: numeral.sign == -1,
round_up: round_up,
base: numeral.base
)
if numeral.zero? && simplifying?
digits = []
point = 0
end
normalization = simplifying? ? :exact : :approximate
Numeral[digits, point: point, base: numeral.base, sign: numeral.sign, normalize: normalization]
end | ruby | def adjust(numeral, round_up)
check_base numeral
point, digits = Flt::Support.adjust_digits(
numeral.point, numeral.digits.digits_array,
round_mode: @mode,
negative: numeral.sign == -1,
round_up: round_up,
base: numeral.base
)
if numeral.zero? && simplifying?
digits = []
point = 0
end
normalization = simplifying? ? :exact : :approximate
Numeral[digits, point: point, base: numeral.base, sign: numeral.sign, normalize: normalization]
end | [
"def",
"adjust",
"(",
"numeral",
",",
"round_up",
")",
"check_base",
"numeral",
"point",
",",
"digits",
"=",
"Flt",
"::",
"Support",
".",
"adjust_digits",
"(",
"numeral",
".",
"point",
",",
"numeral",
".",
"digits",
".",
"digits_array",
",",
"round_mode",
":",
"@mode",
",",
"negative",
":",
"numeral",
".",
"sign",
"==",
"-",
"1",
",",
"round_up",
":",
"round_up",
",",
"base",
":",
"numeral",
".",
"base",
")",
"if",
"numeral",
".",
"zero?",
"&&",
"simplifying?",
"digits",
"=",
"[",
"]",
"point",
"=",
"0",
"end",
"normalization",
"=",
"simplifying?",
"?",
":exact",
":",
":approximate",
"Numeral",
"[",
"digits",
",",
"point",
":",
"point",
",",
"base",
":",
"numeral",
".",
"base",
",",
"sign",
":",
"numeral",
".",
"sign",
",",
"normalize",
":",
"normalization",
"]",
"end"
] | Adjust a truncated numeral using the round-up information | [
"Adjust",
"a",
"truncated",
"numeral",
"using",
"the",
"round",
"-",
"up",
"information"
] | a195e75f689af926537f791441bf8d11590c99c0 | https://github.com/jgoizueta/numerals/blob/a195e75f689af926537f791441bf8d11590c99c0/lib/numerals/rounding.rb#L293-L308 | train |
kmcd/active_record-tableless_model | lib/active_record-tableless_model.rb | ActiveRecord::Base::TablelessModel.ClassMethods.column | def column(name, sql_type = :text, default = nil, null = true)
columns << ActiveRecord::ConnectionAdapters::Column.new(name.to_s, default, sql_type.to_s, null)
end | ruby | def column(name, sql_type = :text, default = nil, null = true)
columns << ActiveRecord::ConnectionAdapters::Column.new(name.to_s, default, sql_type.to_s, null)
end | [
"def",
"column",
"(",
"name",
",",
"sql_type",
"=",
":text",
",",
"default",
"=",
"nil",
",",
"null",
"=",
"true",
")",
"columns",
"<<",
"ActiveRecord",
"::",
"ConnectionAdapters",
"::",
"Column",
".",
"new",
"(",
"name",
".",
"to_s",
",",
"default",
",",
"sql_type",
".",
"to_s",
",",
"null",
")",
"end"
] | Creates an attribute corresponding to a database column.
N.B No table is created in the database
== Arguments
<tt>name</tt> :: column name, such as supplier_id in supplier_id int(11).
<tt>default</tt> :: type-casted default value, such as new in sales_stage varchar(20) default 'new'.
<tt>sql_type</tt> :: used to extract the column length, if necessary. For example 60 in company_name varchar(60). null determines if this column allows NULL values.
== Usage
class Task < ActiveRecord::Base
no_table
column :description, :text
column :description, :string, 'foo', false
end | [
"Creates",
"an",
"attribute",
"corresponding",
"to",
"a",
"database",
"column",
".",
"N",
".",
"B",
"No",
"table",
"is",
"created",
"in",
"the",
"database"
] | 42b84a0b2001bd3f000685bab7920c6fbf60e21b | https://github.com/kmcd/active_record-tableless_model/blob/42b84a0b2001bd3f000685bab7920c6fbf60e21b/lib/active_record-tableless_model.rb#L31-L33 | train |
rich-dtk/dtk-common | lib/gitolite/manager.rb | Gitolite.Manager.create_user | def create_user(username, rsa_pub_key, rsa_pub_key_name)
key_name = "#{username}@#{rsa_pub_key_name}"
key_path = @configuration.user_key_path(key_name)
if users_public_keys().include?(key_path)
raise ::Gitolite::Duplicate, "Public key (#{rsa_pub_key_name}) already exists for user (#{username}) on gitolite server"
end
add_commit_file(key_path,rsa_pub_key, "Added public key (#{rsa_pub_key_name}) for user (#{username}) ")
key_path
end | ruby | def create_user(username, rsa_pub_key, rsa_pub_key_name)
key_name = "#{username}@#{rsa_pub_key_name}"
key_path = @configuration.user_key_path(key_name)
if users_public_keys().include?(key_path)
raise ::Gitolite::Duplicate, "Public key (#{rsa_pub_key_name}) already exists for user (#{username}) on gitolite server"
end
add_commit_file(key_path,rsa_pub_key, "Added public key (#{rsa_pub_key_name}) for user (#{username}) ")
key_path
end | [
"def",
"create_user",
"(",
"username",
",",
"rsa_pub_key",
",",
"rsa_pub_key_name",
")",
"key_name",
"=",
"\"#{username}@#{rsa_pub_key_name}\"",
"key_path",
"=",
"@configuration",
".",
"user_key_path",
"(",
"key_name",
")",
"if",
"users_public_keys",
"(",
")",
".",
"include?",
"(",
"key_path",
")",
"raise",
"::",
"Gitolite",
"::",
"Duplicate",
",",
"\"Public key (#{rsa_pub_key_name}) already exists for user (#{username}) on gitolite server\"",
"end",
"add_commit_file",
"(",
"key_path",
",",
"rsa_pub_key",
",",
"\"Added public key (#{rsa_pub_key_name}) for user (#{username}) \"",
")",
"key_path",
"end"
] | this should be depracated | [
"this",
"should",
"be",
"depracated"
] | 18d312092e9060f01d271a603ad4b0c9bef318b1 | https://github.com/rich-dtk/dtk-common/blob/18d312092e9060f01d271a603ad4b0c9bef318b1/lib/gitolite/manager.rb#L41-L52 | train |
triglav-dataflow/triglav-client-ruby | lib/triglav_client/api/messages_api.rb | TriglavClient.MessagesApi.send_messages | def send_messages(messages, opts = {})
data, _status_code, _headers = send_messages_with_http_info(messages, opts)
return data
end | ruby | def send_messages(messages, opts = {})
data, _status_code, _headers = send_messages_with_http_info(messages, opts)
return data
end | [
"def",
"send_messages",
"(",
"messages",
",",
"opts",
"=",
"{",
"}",
")",
"data",
",",
"_status_code",
",",
"_headers",
"=",
"send_messages_with_http_info",
"(",
"messages",
",",
"opts",
")",
"return",
"data",
"end"
] | Enqueues new messages
@param messages Messages to enqueue
@param [Hash] opts the optional parameters
@return [BulkinsertResponse] | [
"Enqueues",
"new",
"messages"
] | b2f3781d65ee032ba96eb703fbd789c713a5e0bd | https://github.com/triglav-dataflow/triglav-client-ruby/blob/b2f3781d65ee032ba96eb703fbd789c713a5e0bd/lib/triglav_client/api/messages_api.rb#L156-L159 | train |
buzzware/buzztools | lib/buzztools/file.rb | Buzztools.File.real_path | def real_path(aPath)
(path = Pathname.new(::File.expand_path(aPath))) && path.realpath.to_s
end | ruby | def real_path(aPath)
(path = Pathname.new(::File.expand_path(aPath))) && path.realpath.to_s
end | [
"def",
"real_path",
"(",
"aPath",
")",
"(",
"path",
"=",
"Pathname",
".",
"new",
"(",
"::",
"File",
".",
"expand_path",
"(",
"aPath",
")",
")",
")",
"&&",
"path",
".",
"realpath",
".",
"to_s",
"end"
] | make path real according to file system | [
"make",
"path",
"real",
"according",
"to",
"file",
"system"
] | 0823721974d521330ceffe099368ed8cac6209c3 | https://github.com/buzzware/buzztools/blob/0823721974d521330ceffe099368ed8cac6209c3/lib/buzztools/file.rb#L64-L66 | train |
buzzware/buzztools | lib/buzztools/file.rb | Buzztools.File.expand_magic_path | def expand_magic_path(aPath,aBasePath=nil)
aBasePath ||= Dir.pwd
path = aPath
if path.begins_with?('...')
rel_part = path.split3(/\.\.\.[\/\\]/)[2]
return find_upwards(aBasePath,rel_part)
end
path_combine(aBasePath,aPath)
end | ruby | def expand_magic_path(aPath,aBasePath=nil)
aBasePath ||= Dir.pwd
path = aPath
if path.begins_with?('...')
rel_part = path.split3(/\.\.\.[\/\\]/)[2]
return find_upwards(aBasePath,rel_part)
end
path_combine(aBasePath,aPath)
end | [
"def",
"expand_magic_path",
"(",
"aPath",
",",
"aBasePath",
"=",
"nil",
")",
"aBasePath",
"||=",
"Dir",
".",
"pwd",
"path",
"=",
"aPath",
"if",
"path",
".",
"begins_with?",
"(",
"'...'",
")",
"rel_part",
"=",
"path",
".",
"split3",
"(",
"/",
"\\.",
"\\.",
"\\.",
"\\/",
"\\\\",
"/",
")",
"[",
"2",
"]",
"return",
"find_upwards",
"(",
"aBasePath",
",",
"rel_part",
")",
"end",
"path_combine",
"(",
"aBasePath",
",",
"aPath",
")",
"end"
] | allows special symbols in path
currently only ... supported, which looks upward in the filesystem for the following relative path from the basepath | [
"allows",
"special",
"symbols",
"in",
"path",
"currently",
"only",
"...",
"supported",
"which",
"looks",
"upward",
"in",
"the",
"filesystem",
"for",
"the",
"following",
"relative",
"path",
"from",
"the",
"basepath"
] | 0823721974d521330ceffe099368ed8cac6209c3 | https://github.com/buzzware/buzztools/blob/0823721974d521330ceffe099368ed8cac6209c3/lib/buzztools/file.rb#L86-L94 | train |
equallevel/grapple | lib/grapple/html_table_builder.rb | Grapple.HtmlTableBuilder.container | def container(inner_html)
html = ''
html << before_container
html << template.tag('div', container_attributes, true) + "\n"
html << inner_html
html << "</div>\n"
html << after_container
return html.html_safe
end | ruby | def container(inner_html)
html = ''
html << before_container
html << template.tag('div', container_attributes, true) + "\n"
html << inner_html
html << "</div>\n"
html << after_container
return html.html_safe
end | [
"def",
"container",
"(",
"inner_html",
")",
"html",
"=",
"''",
"html",
"<<",
"before_container",
"html",
"<<",
"template",
".",
"tag",
"(",
"'div'",
",",
"container_attributes",
",",
"true",
")",
"+",
"\"\\n\"",
"html",
"<<",
"inner_html",
"html",
"<<",
"\"</div>\\n\"",
"html",
"<<",
"after_container",
"return",
"html",
".",
"html_safe",
"end"
] | Wrap the table in a div | [
"Wrap",
"the",
"table",
"in",
"a",
"div"
] | 65dc1c141adaa3342f0985f4b09d34f6de49e31f | https://github.com/equallevel/grapple/blob/65dc1c141adaa3342f0985f4b09d34f6de49e31f/lib/grapple/html_table_builder.rb#L18-L26 | train |
blambeau/yargi | lib/yargi/markable.rb | Yargi.Markable.add_marks | def add_marks(marks=nil)
marks.each_pair {|k,v| self[k]=v} if marks
if block_given?
result = yield self
add_marks(result) if Hash===result
end
end | ruby | def add_marks(marks=nil)
marks.each_pair {|k,v| self[k]=v} if marks
if block_given?
result = yield self
add_marks(result) if Hash===result
end
end | [
"def",
"add_marks",
"(",
"marks",
"=",
"nil",
")",
"marks",
".",
"each_pair",
"{",
"|",
"k",
",",
"v",
"|",
"self",
"[",
"k",
"]",
"=",
"v",
"}",
"if",
"marks",
"if",
"block_given?",
"result",
"=",
"yield",
"self",
"add_marks",
"(",
"result",
")",
"if",
"Hash",
"===",
"result",
"end",
"end"
] | Add all marks provided by a Hash instance _marks_. | [
"Add",
"all",
"marks",
"provided",
"by",
"a",
"Hash",
"instance",
"_marks_",
"."
] | 100141e96d245a0a8211cd4f7590909be149bc3c | https://github.com/blambeau/yargi/blob/100141e96d245a0a8211cd4f7590909be149bc3c/lib/yargi/markable.rb#L46-L52 | train |
blambeau/yargi | lib/yargi/markable.rb | Yargi.Markable.to_h | def to_h(nonil=true)
return {} unless @marks
marks = @marks.dup
if nonil
marks.delete_if {|k,v| v.nil?}
end
marks
end | ruby | def to_h(nonil=true)
return {} unless @marks
marks = @marks.dup
if nonil
marks.delete_if {|k,v| v.nil?}
end
marks
end | [
"def",
"to_h",
"(",
"nonil",
"=",
"true",
")",
"return",
"{",
"}",
"unless",
"@marks",
"marks",
"=",
"@marks",
".",
"dup",
"if",
"nonil",
"marks",
".",
"delete_if",
"{",
"|",
"k",
",",
"v",
"|",
"v",
".",
"nil?",
"}",
"end",
"marks",
"end"
] | Converts this Markable to a Hash. When _nonil_ is true, nil mark values
do not lead to hash entries. | [
"Converts",
"this",
"Markable",
"to",
"a",
"Hash",
".",
"When",
"_nonil_",
"is",
"true",
"nil",
"mark",
"values",
"do",
"not",
"lead",
"to",
"hash",
"entries",
"."
] | 100141e96d245a0a8211cd4f7590909be149bc3c | https://github.com/blambeau/yargi/blob/100141e96d245a0a8211cd4f7590909be149bc3c/lib/yargi/markable.rb#L57-L64 | train |
DaQwest/dq-readability | lib/dq-readability.rb | DQReadability.Document.author | def author
# Let's grab this author:
# <meta name="dc.creator" content="Finch - http://www.getfinch.com" />
author_elements = @html.xpath('//meta[@name = "dc.creator"]')
unless author_elements.empty?
author_elements.each do |element|
if element['content']
return element['content'].strip
end
end
end
# Now let's try to grab this
# <span class="byline author vcard"><span>By</span><cite class="fn">Austin Fonacier</cite></span>
# <div class="author">By</div><div class="author vcard"><a class="url fn" href="http://austinlivesinyoapp.com/">Austin Fonacier</a></div>
author_elements = @html.xpath('//*[contains(@class, "vcard")]//*[contains(@class, "fn")]')
unless author_elements.empty?
author_elements.each do |element|
if element.text
return element.text.strip
end
end
end
# Now let's try to grab this
# <a rel="author" href="http://dbanksdesign.com">Danny Banks (rel)</a>
# TODO: strip out the (rel)?
author_elements = @html.xpath('//a[@rel = "author"]')
unless author_elements.empty?
author_elements.each do |element|
if element.text
return element.text.strip
end
end
end
author_elements = @html.xpath('//*[@id = "author"]')
unless author_elements.empty?
author_elements.each do |element|
if element.text
return element.text.strip
end
end
end
end | ruby | def author
# Let's grab this author:
# <meta name="dc.creator" content="Finch - http://www.getfinch.com" />
author_elements = @html.xpath('//meta[@name = "dc.creator"]')
unless author_elements.empty?
author_elements.each do |element|
if element['content']
return element['content'].strip
end
end
end
# Now let's try to grab this
# <span class="byline author vcard"><span>By</span><cite class="fn">Austin Fonacier</cite></span>
# <div class="author">By</div><div class="author vcard"><a class="url fn" href="http://austinlivesinyoapp.com/">Austin Fonacier</a></div>
author_elements = @html.xpath('//*[contains(@class, "vcard")]//*[contains(@class, "fn")]')
unless author_elements.empty?
author_elements.each do |element|
if element.text
return element.text.strip
end
end
end
# Now let's try to grab this
# <a rel="author" href="http://dbanksdesign.com">Danny Banks (rel)</a>
# TODO: strip out the (rel)?
author_elements = @html.xpath('//a[@rel = "author"]')
unless author_elements.empty?
author_elements.each do |element|
if element.text
return element.text.strip
end
end
end
author_elements = @html.xpath('//*[@id = "author"]')
unless author_elements.empty?
author_elements.each do |element|
if element.text
return element.text.strip
end
end
end
end | [
"def",
"author",
"author_elements",
"=",
"@html",
".",
"xpath",
"(",
"'//meta[@name = \"dc.creator\"]'",
")",
"unless",
"author_elements",
".",
"empty?",
"author_elements",
".",
"each",
"do",
"|",
"element",
"|",
"if",
"element",
"[",
"'content'",
"]",
"return",
"element",
"[",
"'content'",
"]",
".",
"strip",
"end",
"end",
"end",
"author_elements",
"=",
"@html",
".",
"xpath",
"(",
"'//*[contains(@class, \"vcard\")]//*[contains(@class, \"fn\")]'",
")",
"unless",
"author_elements",
".",
"empty?",
"author_elements",
".",
"each",
"do",
"|",
"element",
"|",
"if",
"element",
".",
"text",
"return",
"element",
".",
"text",
".",
"strip",
"end",
"end",
"end",
"author_elements",
"=",
"@html",
".",
"xpath",
"(",
"'//a[@rel = \"author\"]'",
")",
"unless",
"author_elements",
".",
"empty?",
"author_elements",
".",
"each",
"do",
"|",
"element",
"|",
"if",
"element",
".",
"text",
"return",
"element",
".",
"text",
".",
"strip",
"end",
"end",
"end",
"author_elements",
"=",
"@html",
".",
"xpath",
"(",
"'//*[@id = \"author\"]'",
")",
"unless",
"author_elements",
".",
"empty?",
"author_elements",
".",
"each",
"do",
"|",
"element",
"|",
"if",
"element",
".",
"text",
"return",
"element",
".",
"text",
".",
"strip",
"end",
"end",
"end",
"end"
] | Look through the @html document looking for the author
Precedence Information here on the wiki: (TODO attach wiki URL if it is accepted)
Returns nil if no author is detected | [
"Look",
"through",
"the"
] | 6fe7830e1aba4867b4a263ee664d0987e8df039a | https://github.com/DaQwest/dq-readability/blob/6fe7830e1aba4867b4a263ee664d0987e8df039a/lib/dq-readability.rb#L262-L306 | train |
barkerest/barkest_core | app/helpers/barkest_core/users_helper.rb | BarkestCore.UsersHelper.gravatar_for | def gravatar_for(user, options = {})
options = { size: 80, default: :identicon }.merge(options || {})
options[:default] = options[:default].to_s.to_sym unless options[:default].nil? || options[:default].is_a?(Symbol)
gravatar_id = Digest::MD5::hexdigest(user.email.downcase)
size = options[:size]
default = [:mm, :identicon, :monsterid, :wavatar, :retro].include?(options[:default]) ? "&d=#{options[:default]}" : ''
gravatar_url = "https://secure.gravatar.com/avatar/#{gravatar_id}?s=#{size}#{default}"
image_tag(gravatar_url, alt: user.name, class: 'gravatar', style: "width: #{size}px, height: #{size}px")
end | ruby | def gravatar_for(user, options = {})
options = { size: 80, default: :identicon }.merge(options || {})
options[:default] = options[:default].to_s.to_sym unless options[:default].nil? || options[:default].is_a?(Symbol)
gravatar_id = Digest::MD5::hexdigest(user.email.downcase)
size = options[:size]
default = [:mm, :identicon, :monsterid, :wavatar, :retro].include?(options[:default]) ? "&d=#{options[:default]}" : ''
gravatar_url = "https://secure.gravatar.com/avatar/#{gravatar_id}?s=#{size}#{default}"
image_tag(gravatar_url, alt: user.name, class: 'gravatar', style: "width: #{size}px, height: #{size}px")
end | [
"def",
"gravatar_for",
"(",
"user",
",",
"options",
"=",
"{",
"}",
")",
"options",
"=",
"{",
"size",
":",
"80",
",",
"default",
":",
":identicon",
"}",
".",
"merge",
"(",
"options",
"||",
"{",
"}",
")",
"options",
"[",
":default",
"]",
"=",
"options",
"[",
":default",
"]",
".",
"to_s",
".",
"to_sym",
"unless",
"options",
"[",
":default",
"]",
".",
"nil?",
"||",
"options",
"[",
":default",
"]",
".",
"is_a?",
"(",
"Symbol",
")",
"gravatar_id",
"=",
"Digest",
"::",
"MD5",
"::",
"hexdigest",
"(",
"user",
".",
"email",
".",
"downcase",
")",
"size",
"=",
"options",
"[",
":size",
"]",
"default",
"=",
"[",
":mm",
",",
":identicon",
",",
":monsterid",
",",
":wavatar",
",",
":retro",
"]",
".",
"include?",
"(",
"options",
"[",
":default",
"]",
")",
"?",
"\"&d=#{options[:default]}\"",
":",
"''",
"gravatar_url",
"=",
"\"https://secure.gravatar.com/avatar/#{gravatar_id}?s=#{size}#{default}\"",
"image_tag",
"(",
"gravatar_url",
",",
"alt",
":",
"user",
".",
"name",
",",
"class",
":",
"'gravatar'",
",",
"style",
":",
"\"width: #{size}px, height: #{size}px\"",
")",
"end"
] | Returns the Gravatar for the given user.
Based on the tutorial from [www.railstutorial.org](www.railstutorial.org).
The +user+ is the user you want to get the gravatar for.
Valid options:
* +size+ The size (in pixels) for the returned gravatar. The gravatar will be a square image using this
value as both the width and height. The default is 80 pixels.
* +default+ The default image to return when no image is set. This can be nil, :mm, :identicon, :monsterid,
:wavatar, or :retro. The default is :identicon. | [
"Returns",
"the",
"Gravatar",
"for",
"the",
"given",
"user",
"."
] | 3eeb025ec870888cacbc9bae252a39ebf9295f61 | https://github.com/barkerest/barkest_core/blob/3eeb025ec870888cacbc9bae252a39ebf9295f61/app/helpers/barkest_core/users_helper.rb#L21-L29 | train |
ujjwalt/neon | lib/helpers/argument_helpers.rb | Neon.ArgumentHelpers.extract_session | def extract_session(args)
if args.last.is_a?(Session::Rest) || args.last.is_a?(Session::Embedded)
args.pop
else
Session.current
end
end | ruby | def extract_session(args)
if args.last.is_a?(Session::Rest) || args.last.is_a?(Session::Embedded)
args.pop
else
Session.current
end
end | [
"def",
"extract_session",
"(",
"args",
")",
"if",
"args",
".",
"last",
".",
"is_a?",
"(",
"Session",
"::",
"Rest",
")",
"||",
"args",
".",
"last",
".",
"is_a?",
"(",
"Session",
"::",
"Embedded",
")",
"args",
".",
"pop",
"else",
"Session",
".",
"current",
"end",
"end"
] | Extracts a session from the array of arguments if one exists at the end.
@param args [Array] an array of arguments of any type.
@return [Session] a session if the last argument is a valid session and pops it out of args.
Otherwise it returns the current session. | [
"Extracts",
"a",
"session",
"from",
"the",
"array",
"of",
"arguments",
"if",
"one",
"exists",
"at",
"the",
"end",
"."
] | 609769b16f051a100809131df105df29f98037fc | https://github.com/ujjwalt/neon/blob/609769b16f051a100809131df105df29f98037fc/lib/helpers/argument_helpers.rb#L11-L17 | train |
omegainteractive/comfypress | lib/comfypress/extensions/is_mirrored.rb | ComfyPress::IsMirrored.InstanceMethods.mirrors | def mirrors
return [] unless self.site.is_mirrored?
(Cms::Site.mirrored - [self.site]).collect do |site|
case self
when Cms::Layout then site.layouts.find_by_identifier(self.identifier)
when Cms::Page then site.pages.find_by_full_path(self.full_path)
when Cms::Snippet then site.snippets.find_by_identifier(self.identifier)
end
end.compact
end | ruby | def mirrors
return [] unless self.site.is_mirrored?
(Cms::Site.mirrored - [self.site]).collect do |site|
case self
when Cms::Layout then site.layouts.find_by_identifier(self.identifier)
when Cms::Page then site.pages.find_by_full_path(self.full_path)
when Cms::Snippet then site.snippets.find_by_identifier(self.identifier)
end
end.compact
end | [
"def",
"mirrors",
"return",
"[",
"]",
"unless",
"self",
".",
"site",
".",
"is_mirrored?",
"(",
"Cms",
"::",
"Site",
".",
"mirrored",
"-",
"[",
"self",
".",
"site",
"]",
")",
".",
"collect",
"do",
"|",
"site",
"|",
"case",
"self",
"when",
"Cms",
"::",
"Layout",
"then",
"site",
".",
"layouts",
".",
"find_by_identifier",
"(",
"self",
".",
"identifier",
")",
"when",
"Cms",
"::",
"Page",
"then",
"site",
".",
"pages",
".",
"find_by_full_path",
"(",
"self",
".",
"full_path",
")",
"when",
"Cms",
"::",
"Snippet",
"then",
"site",
".",
"snippets",
".",
"find_by_identifier",
"(",
"self",
".",
"identifier",
")",
"end",
"end",
".",
"compact",
"end"
] | Mirrors of the object found on other sites | [
"Mirrors",
"of",
"the",
"object",
"found",
"on",
"other",
"sites"
] | 3b64699bf16774b636cb13ecd89281f6e2acb264 | https://github.com/omegainteractive/comfypress/blob/3b64699bf16774b636cb13ecd89281f6e2acb264/lib/comfypress/extensions/is_mirrored.rb#L21-L30 | train |
omegainteractive/comfypress | lib/comfypress/extensions/is_mirrored.rb | ComfyPress::IsMirrored.InstanceMethods.sync_mirror | def sync_mirror
return if self.is_mirrored || !self.site.is_mirrored?
(Cms::Site.mirrored - [self.site]).each do |site|
mirror = case self
when Cms::Layout
m = site.layouts.find_by_identifier(self.identifier_was || self.identifier) || site.layouts.new
m.attributes = {
:identifier => self.identifier,
:parent_id => site.layouts.find_by_identifier(self.parent.try(:identifier)).try(:id)
}
m
when Cms::Page
m = site.pages.find_by_full_path(self.full_path_was || self.full_path) || site.pages.new
m.attributes = {
:slug => self.slug,
:label => self.slug.blank?? self.label : m.label,
:parent_id => site.pages.find_by_full_path(self.parent.try(:full_path)).try(:id),
:layout => site.layouts.find_by_identifier(self.layout.try(:identifier))
}
m
when Cms::Snippet
m = site.snippets.find_by_identifier(self.identifier_was || self.identifier) || site.snippets.new
m.attributes = {
:identifier => self.identifier
}
m
end
mirror.is_mirrored = true
begin
mirror.save!
rescue ActiveRecord::RecordInvalid
logger.detailed_error($!)
end
end
end | ruby | def sync_mirror
return if self.is_mirrored || !self.site.is_mirrored?
(Cms::Site.mirrored - [self.site]).each do |site|
mirror = case self
when Cms::Layout
m = site.layouts.find_by_identifier(self.identifier_was || self.identifier) || site.layouts.new
m.attributes = {
:identifier => self.identifier,
:parent_id => site.layouts.find_by_identifier(self.parent.try(:identifier)).try(:id)
}
m
when Cms::Page
m = site.pages.find_by_full_path(self.full_path_was || self.full_path) || site.pages.new
m.attributes = {
:slug => self.slug,
:label => self.slug.blank?? self.label : m.label,
:parent_id => site.pages.find_by_full_path(self.parent.try(:full_path)).try(:id),
:layout => site.layouts.find_by_identifier(self.layout.try(:identifier))
}
m
when Cms::Snippet
m = site.snippets.find_by_identifier(self.identifier_was || self.identifier) || site.snippets.new
m.attributes = {
:identifier => self.identifier
}
m
end
mirror.is_mirrored = true
begin
mirror.save!
rescue ActiveRecord::RecordInvalid
logger.detailed_error($!)
end
end
end | [
"def",
"sync_mirror",
"return",
"if",
"self",
".",
"is_mirrored",
"||",
"!",
"self",
".",
"site",
".",
"is_mirrored?",
"(",
"Cms",
"::",
"Site",
".",
"mirrored",
"-",
"[",
"self",
".",
"site",
"]",
")",
".",
"each",
"do",
"|",
"site",
"|",
"mirror",
"=",
"case",
"self",
"when",
"Cms",
"::",
"Layout",
"m",
"=",
"site",
".",
"layouts",
".",
"find_by_identifier",
"(",
"self",
".",
"identifier_was",
"||",
"self",
".",
"identifier",
")",
"||",
"site",
".",
"layouts",
".",
"new",
"m",
".",
"attributes",
"=",
"{",
":identifier",
"=>",
"self",
".",
"identifier",
",",
":parent_id",
"=>",
"site",
".",
"layouts",
".",
"find_by_identifier",
"(",
"self",
".",
"parent",
".",
"try",
"(",
":identifier",
")",
")",
".",
"try",
"(",
":id",
")",
"}",
"m",
"when",
"Cms",
"::",
"Page",
"m",
"=",
"site",
".",
"pages",
".",
"find_by_full_path",
"(",
"self",
".",
"full_path_was",
"||",
"self",
".",
"full_path",
")",
"||",
"site",
".",
"pages",
".",
"new",
"m",
".",
"attributes",
"=",
"{",
":slug",
"=>",
"self",
".",
"slug",
",",
":label",
"=>",
"self",
".",
"slug",
".",
"blank?",
"?",
"self",
".",
"label",
":",
"m",
".",
"label",
",",
":parent_id",
"=>",
"site",
".",
"pages",
".",
"find_by_full_path",
"(",
"self",
".",
"parent",
".",
"try",
"(",
":full_path",
")",
")",
".",
"try",
"(",
":id",
")",
",",
":layout",
"=>",
"site",
".",
"layouts",
".",
"find_by_identifier",
"(",
"self",
".",
"layout",
".",
"try",
"(",
":identifier",
")",
")",
"}",
"m",
"when",
"Cms",
"::",
"Snippet",
"m",
"=",
"site",
".",
"snippets",
".",
"find_by_identifier",
"(",
"self",
".",
"identifier_was",
"||",
"self",
".",
"identifier",
")",
"||",
"site",
".",
"snippets",
".",
"new",
"m",
".",
"attributes",
"=",
"{",
":identifier",
"=>",
"self",
".",
"identifier",
"}",
"m",
"end",
"mirror",
".",
"is_mirrored",
"=",
"true",
"begin",
"mirror",
".",
"save!",
"rescue",
"ActiveRecord",
"::",
"RecordInvalid",
"logger",
".",
"detailed_error",
"(",
"$!",
")",
"end",
"end",
"end"
] | Creating or updating a mirror object. Relationships are mirrored
but content is unique. When updating need to grab mirrors based on
self.slug_was, new objects will use self.slug. | [
"Creating",
"or",
"updating",
"a",
"mirror",
"object",
".",
"Relationships",
"are",
"mirrored",
"but",
"content",
"is",
"unique",
".",
"When",
"updating",
"need",
"to",
"grab",
"mirrors",
"based",
"on",
"self",
".",
"slug_was",
"new",
"objects",
"will",
"use",
"self",
".",
"slug",
"."
] | 3b64699bf16774b636cb13ecd89281f6e2acb264 | https://github.com/omegainteractive/comfypress/blob/3b64699bf16774b636cb13ecd89281f6e2acb264/lib/comfypress/extensions/is_mirrored.rb#L35-L71 | train |
omegainteractive/comfypress | lib/comfypress/extensions/is_mirrored.rb | ComfyPress::IsMirrored.InstanceMethods.destroy_mirror | def destroy_mirror
return if self.is_mirrored || !self.site.is_mirrored?
mirrors.each do |mirror|
mirror.is_mirrored = true
mirror.destroy
end
end | ruby | def destroy_mirror
return if self.is_mirrored || !self.site.is_mirrored?
mirrors.each do |mirror|
mirror.is_mirrored = true
mirror.destroy
end
end | [
"def",
"destroy_mirror",
"return",
"if",
"self",
".",
"is_mirrored",
"||",
"!",
"self",
".",
"site",
".",
"is_mirrored?",
"mirrors",
".",
"each",
"do",
"|",
"mirror",
"|",
"mirror",
".",
"is_mirrored",
"=",
"true",
"mirror",
".",
"destroy",
"end",
"end"
] | Mirrors should be destroyed | [
"Mirrors",
"should",
"be",
"destroyed"
] | 3b64699bf16774b636cb13ecd89281f6e2acb264 | https://github.com/omegainteractive/comfypress/blob/3b64699bf16774b636cb13ecd89281f6e2acb264/lib/comfypress/extensions/is_mirrored.rb#L74-L80 | train |
barkerest/shells | lib/shells/bash_common.rb | Shells.BashCommon.read_file | def read_file(path, use_method = nil)
if use_method
use_method = use_method.to_sym
raise ArgumentError, "use_method (#{use_method.inspect}) is not a valid method." unless file_methods.include?(use_method)
raise Shells::ShellError, "The #{use_method} binary is not available with this shell." unless which(use_method)
send "read_file_#{use_method}", path
elsif default_file_method
return send "read_file_#{default_file_method}", path
else
raise Shells::ShellError, 'No supported binary to encode/decode files.'
end
end | ruby | def read_file(path, use_method = nil)
if use_method
use_method = use_method.to_sym
raise ArgumentError, "use_method (#{use_method.inspect}) is not a valid method." unless file_methods.include?(use_method)
raise Shells::ShellError, "The #{use_method} binary is not available with this shell." unless which(use_method)
send "read_file_#{use_method}", path
elsif default_file_method
return send "read_file_#{default_file_method}", path
else
raise Shells::ShellError, 'No supported binary to encode/decode files.'
end
end | [
"def",
"read_file",
"(",
"path",
",",
"use_method",
"=",
"nil",
")",
"if",
"use_method",
"use_method",
"=",
"use_method",
".",
"to_sym",
"raise",
"ArgumentError",
",",
"\"use_method (#{use_method.inspect}) is not a valid method.\"",
"unless",
"file_methods",
".",
"include?",
"(",
"use_method",
")",
"raise",
"Shells",
"::",
"ShellError",
",",
"\"The #{use_method} binary is not available with this shell.\"",
"unless",
"which",
"(",
"use_method",
")",
"send",
"\"read_file_#{use_method}\"",
",",
"path",
"elsif",
"default_file_method",
"return",
"send",
"\"read_file_#{default_file_method}\"",
",",
"path",
"else",
"raise",
"Shells",
"::",
"ShellError",
",",
"'No supported binary to encode/decode files.'",
"end",
"end"
] | Reads from a file on the device. | [
"Reads",
"from",
"a",
"file",
"on",
"the",
"device",
"."
] | 674a0254f48cea01b0ae8979933f13892e398506 | https://github.com/barkerest/shells/blob/674a0254f48cea01b0ae8979933f13892e398506/lib/shells/bash_common.rb#L10-L21 | train |
barkerest/shells | lib/shells/bash_common.rb | Shells.BashCommon.sudo_exec | def sudo_exec(command, options = {}, &block)
sudo_prompt = '[sp:'
sudo_match = /\n\[sp:$/m
sudo_strip = /\[sp:[^\n]*\n/m
ret = exec("sudo -p \"#{sudo_prompt}\" bash -c \"#{command.gsub('"', '\\"')}\"", options) do |data,type|
test_data = data.to_s
desired_length = sudo_prompt.length + 1 # prefix a NL before the prompt.
# pull from the current stdout to get the full test data, but only if we received some new data.
if test_data.length > 0 && test_data.length < desired_length
test_data = stdout[-desired_length..-1].to_s
end
if test_data =~ sudo_match
self.options[:password]
else
if block
block.call(data, type)
else
nil
end
end
end
# remove the sudo prompts.
ret.gsub(sudo_strip, '')
end | ruby | def sudo_exec(command, options = {}, &block)
sudo_prompt = '[sp:'
sudo_match = /\n\[sp:$/m
sudo_strip = /\[sp:[^\n]*\n/m
ret = exec("sudo -p \"#{sudo_prompt}\" bash -c \"#{command.gsub('"', '\\"')}\"", options) do |data,type|
test_data = data.to_s
desired_length = sudo_prompt.length + 1 # prefix a NL before the prompt.
# pull from the current stdout to get the full test data, but only if we received some new data.
if test_data.length > 0 && test_data.length < desired_length
test_data = stdout[-desired_length..-1].to_s
end
if test_data =~ sudo_match
self.options[:password]
else
if block
block.call(data, type)
else
nil
end
end
end
# remove the sudo prompts.
ret.gsub(sudo_strip, '')
end | [
"def",
"sudo_exec",
"(",
"command",
",",
"options",
"=",
"{",
"}",
",",
"&",
"block",
")",
"sudo_prompt",
"=",
"'[sp:'",
"sudo_match",
"=",
"/",
"\\n",
"\\[",
"/m",
"sudo_strip",
"=",
"/",
"\\[",
"\\n",
"\\n",
"/m",
"ret",
"=",
"exec",
"(",
"\"sudo -p \\\"#{sudo_prompt}\\\" bash -c \\\"#{command.gsub('\"', '\\\\\"')}\\\"\"",
",",
"options",
")",
"do",
"|",
"data",
",",
"type",
"|",
"test_data",
"=",
"data",
".",
"to_s",
"desired_length",
"=",
"sudo_prompt",
".",
"length",
"+",
"1",
"if",
"test_data",
".",
"length",
">",
"0",
"&&",
"test_data",
".",
"length",
"<",
"desired_length",
"test_data",
"=",
"stdout",
"[",
"-",
"desired_length",
"..",
"-",
"1",
"]",
".",
"to_s",
"end",
"if",
"test_data",
"=~",
"sudo_match",
"self",
".",
"options",
"[",
":password",
"]",
"else",
"if",
"block",
"block",
".",
"call",
"(",
"data",
",",
"type",
")",
"else",
"nil",
"end",
"end",
"end",
"ret",
".",
"gsub",
"(",
"sudo_strip",
",",
"''",
")",
"end"
] | Executes an elevated command using the 'sudo' command. | [
"Executes",
"an",
"elevated",
"command",
"using",
"the",
"sudo",
"command",
"."
] | 674a0254f48cea01b0ae8979933f13892e398506 | https://github.com/barkerest/shells/blob/674a0254f48cea01b0ae8979933f13892e398506/lib/shells/bash_common.rb#L40-L65 | train |
barkerest/shells | lib/shells/bash_common.rb | Shells.BashCommon.setup_prompt | def setup_prompt #:nodoc:
command = "PS1=#{options[:prompt]}"
sleep 1.0 # let shell initialize fully.
exec_ignore_code command, silence_timeout: 10, command_timeout: 10, timeout_error: true, get_output: false
end | ruby | def setup_prompt #:nodoc:
command = "PS1=#{options[:prompt]}"
sleep 1.0 # let shell initialize fully.
exec_ignore_code command, silence_timeout: 10, command_timeout: 10, timeout_error: true, get_output: false
end | [
"def",
"setup_prompt",
"command",
"=",
"\"PS1=#{options[:prompt]}\"",
"sleep",
"1.0",
"exec_ignore_code",
"command",
",",
"silence_timeout",
":",
"10",
",",
"command_timeout",
":",
"10",
",",
"timeout_error",
":",
"true",
",",
"get_output",
":",
"false",
"end"
] | Uses the PS1= command to set the prompt for the shell. | [
"Uses",
"the",
"PS1",
"=",
"command",
"to",
"set",
"the",
"prompt",
"for",
"the",
"shell",
"."
] | 674a0254f48cea01b0ae8979933f13892e398506 | https://github.com/barkerest/shells/blob/674a0254f48cea01b0ae8979933f13892e398506/lib/shells/bash_common.rb#L91-L95 | train |
tclaus/keytechkit.gem | lib/keytechKit/elements/data_dictionary/data_dictionary_handler.rb | KeytechKit.DataDictionaryHandler.getData | def getData(datadictionary_id)
# /DataDictionaries/{ID}|{Name}/data
parameter = { basic_auth: @auth }
response = self.class.get("/datadictionaries/#{datadictionary_id}/data", parameter)
if response.success?
response['Data']
else
raise response.response
end
end | ruby | def getData(datadictionary_id)
# /DataDictionaries/{ID}|{Name}/data
parameter = { basic_auth: @auth }
response = self.class.get("/datadictionaries/#{datadictionary_id}/data", parameter)
if response.success?
response['Data']
else
raise response.response
end
end | [
"def",
"getData",
"(",
"datadictionary_id",
")",
"parameter",
"=",
"{",
"basic_auth",
":",
"@auth",
"}",
"response",
"=",
"self",
".",
"class",
".",
"get",
"(",
"\"/datadictionaries/#{datadictionary_id}/data\"",
",",
"parameter",
")",
"if",
"response",
".",
"success?",
"response",
"[",
"'Data'",
"]",
"else",
"raise",
"response",
".",
"response",
"end",
"end"
] | Returns a hashed value with data | [
"Returns",
"a",
"hashed",
"value",
"with",
"data"
] | caa7a6bee32b75ec18a4004179ae10cb69d148c2 | https://github.com/tclaus/keytechkit.gem/blob/caa7a6bee32b75ec18a4004179ae10cb69d148c2/lib/keytechKit/elements/data_dictionary/data_dictionary_handler.rb#L28-L38 | train |
nepalez/immutability | lib/immutability/object.rb | Immutability.Object.at | def at(point)
ipoint = point.to_i
target = (ipoint < 0) ? (version + ipoint) : ipoint
return unless (0..version).include? target
detect { |state| target.equal? state.version }
end | ruby | def at(point)
ipoint = point.to_i
target = (ipoint < 0) ? (version + ipoint) : ipoint
return unless (0..version).include? target
detect { |state| target.equal? state.version }
end | [
"def",
"at",
"(",
"point",
")",
"ipoint",
"=",
"point",
".",
"to_i",
"target",
"=",
"(",
"ipoint",
"<",
"0",
")",
"?",
"(",
"version",
"+",
"ipoint",
")",
":",
"ipoint",
"return",
"unless",
"(",
"0",
"..",
"version",
")",
".",
"include?",
"target",
"detect",
"{",
"|",
"state",
"|",
"target",
".",
"equal?",
"state",
".",
"version",
"}",
"end"
] | Returns the state of the object at some point in the past
@param [#to_i] point
Either a positive number of target version,
or a negative number of version (snapshots) before the current one
+0+ stands for the first version.
@return [Object, nil] | [
"Returns",
"the",
"state",
"of",
"the",
"object",
"at",
"some",
"point",
"in",
"the",
"past"
] | 6f44a7e3dad9cbc51f40e5ec9b3810d1cc730a10 | https://github.com/nepalez/immutability/blob/6f44a7e3dad9cbc51f40e5ec9b3810d1cc730a10/lib/immutability/object.rb#L55-L61 | train |
notCalle/ruby-keytree | lib/key_tree/forest.rb | KeyTree.Forest.fetch | def fetch(key, *default)
trees.lazy.each do |tree|
catch do |ball|
return tree.fetch(key) { throw ball }
end
end
return yield(key) if block_given?
return default.first unless default.empty?
raise KeyError, %(key not found: "#{key}")
end | ruby | def fetch(key, *default)
trees.lazy.each do |tree|
catch do |ball|
return tree.fetch(key) { throw ball }
end
end
return yield(key) if block_given?
return default.first unless default.empty?
raise KeyError, %(key not found: "#{key}")
end | [
"def",
"fetch",
"(",
"key",
",",
"*",
"default",
")",
"trees",
".",
"lazy",
".",
"each",
"do",
"|",
"tree",
"|",
"catch",
"do",
"|",
"ball",
"|",
"return",
"tree",
".",
"fetch",
"(",
"key",
")",
"{",
"throw",
"ball",
"}",
"end",
"end",
"return",
"yield",
"(",
"key",
")",
"if",
"block_given?",
"return",
"default",
".",
"first",
"unless",
"default",
".",
"empty?",
"raise",
"KeyError",
",",
"%(key not found: \"#{key}\")",
"end"
] | Fetch a value from a forest
:call-seq:
fetch(key) => value
fetch(key, default) => value
fetch(key) { |key| } => value
The first form raises a +KeyError+ unless +key+ has a value. | [
"Fetch",
"a",
"value",
"from",
"a",
"forest"
] | 1a88c902c8b5d14f21fd350338776fc094eae8e3 | https://github.com/notCalle/ruby-keytree/blob/1a88c902c8b5d14f21fd350338776fc094eae8e3/lib/key_tree/forest.rb#L52-L62 | train |
notCalle/ruby-keytree | lib/key_tree/forest.rb | KeyTree.Forest.flatten | def flatten(&merger)
trees.reverse_each.reduce(Tree[]) do |result, tree|
result.merge!(tree, &merger)
end
end | ruby | def flatten(&merger)
trees.reverse_each.reduce(Tree[]) do |result, tree|
result.merge!(tree, &merger)
end
end | [
"def",
"flatten",
"(",
"&",
"merger",
")",
"trees",
".",
"reverse_each",
".",
"reduce",
"(",
"Tree",
"[",
"]",
")",
"do",
"|",
"result",
",",
"tree",
"|",
"result",
".",
"merge!",
"(",
"tree",
",",
"&",
"merger",
")",
"end",
"end"
] | Flattening a forest produces a tree with the equivalent view of key paths | [
"Flattening",
"a",
"forest",
"produces",
"a",
"tree",
"with",
"the",
"equivalent",
"view",
"of",
"key",
"paths"
] | 1a88c902c8b5d14f21fd350338776fc094eae8e3 | https://github.com/notCalle/ruby-keytree/blob/1a88c902c8b5d14f21fd350338776fc094eae8e3/lib/key_tree/forest.rb#L90-L94 | train |
notCalle/ruby-keytree | lib/key_tree/forest.rb | KeyTree.Forest.trees | def trees
Enumerator.new do |yielder|
remaining = [self]
remaining.each do |woods|
next yielder << woods if woods.is_a?(Tree)
woods.each { |wood| remaining << wood }
end
end
end | ruby | def trees
Enumerator.new do |yielder|
remaining = [self]
remaining.each do |woods|
next yielder << woods if woods.is_a?(Tree)
woods.each { |wood| remaining << wood }
end
end
end | [
"def",
"trees",
"Enumerator",
".",
"new",
"do",
"|",
"yielder",
"|",
"remaining",
"=",
"[",
"self",
"]",
"remaining",
".",
"each",
"do",
"|",
"woods",
"|",
"next",
"yielder",
"<<",
"woods",
"if",
"woods",
".",
"is_a?",
"(",
"Tree",
")",
"woods",
".",
"each",
"{",
"|",
"wood",
"|",
"remaining",
"<<",
"wood",
"}",
"end",
"end",
"end"
] | Return a breadth-first Enumerator for all the trees in the forest,
and any nested forests | [
"Return",
"a",
"breadth",
"-",
"first",
"Enumerator",
"for",
"all",
"the",
"trees",
"in",
"the",
"forest",
"and",
"any",
"nested",
"forests"
] | 1a88c902c8b5d14f21fd350338776fc094eae8e3 | https://github.com/notCalle/ruby-keytree/blob/1a88c902c8b5d14f21fd350338776fc094eae8e3/lib/key_tree/forest.rb#L98-L107 | train |
notCalle/ruby-keytree | lib/key_tree/forest.rb | KeyTree.Forest.key_paths | def key_paths
trees.reduce(Set.new) { |result, tree| result.merge(tree.key_paths) }
end | ruby | def key_paths
trees.reduce(Set.new) { |result, tree| result.merge(tree.key_paths) }
end | [
"def",
"key_paths",
"trees",
".",
"reduce",
"(",
"Set",
".",
"new",
")",
"{",
"|",
"result",
",",
"tree",
"|",
"result",
".",
"merge",
"(",
"tree",
".",
"key_paths",
")",
"}",
"end"
] | Return all visible key paths in the forest | [
"Return",
"all",
"visible",
"key",
"paths",
"in",
"the",
"forest"
] | 1a88c902c8b5d14f21fd350338776fc094eae8e3 | https://github.com/notCalle/ruby-keytree/blob/1a88c902c8b5d14f21fd350338776fc094eae8e3/lib/key_tree/forest.rb#L110-L112 | train |
barkerest/incline | lib/incline/extensions/string.rb | Incline::Extensions.String.to_byte_string | def to_byte_string
ret = self.gsub(/\s+/,'')
raise 'Hex string must have even number of characters.' unless ret.size % 2 == 0
raise 'Hex string must only contain 0-9 and A-F characters.' if ret =~ /[^0-9a-fA-F]/
[ret].pack('H*').force_encoding('ascii-8bit')
end | ruby | def to_byte_string
ret = self.gsub(/\s+/,'')
raise 'Hex string must have even number of characters.' unless ret.size % 2 == 0
raise 'Hex string must only contain 0-9 and A-F characters.' if ret =~ /[^0-9a-fA-F]/
[ret].pack('H*').force_encoding('ascii-8bit')
end | [
"def",
"to_byte_string",
"ret",
"=",
"self",
".",
"gsub",
"(",
"/",
"\\s",
"/",
",",
"''",
")",
"raise",
"'Hex string must have even number of characters.'",
"unless",
"ret",
".",
"size",
"%",
"2",
"==",
"0",
"raise",
"'Hex string must only contain 0-9 and A-F characters.'",
"if",
"ret",
"=~",
"/",
"/",
"[",
"ret",
"]",
".",
"pack",
"(",
"'H*'",
")",
".",
"force_encoding",
"(",
"'ascii-8bit'",
")",
"end"
] | Converts a hex string into a byte string.
Whitespace in the string is ignored.
The string must only contain characters valid for hex (ie - 0-9, A-F, a-f).
The string must contain an even number of characters since each character only represents half a byte. | [
"Converts",
"a",
"hex",
"string",
"into",
"a",
"byte",
"string",
"."
] | 1ff08db7aa8ab7f86b223268b700bc67d15bb8aa | https://github.com/barkerest/incline/blob/1ff08db7aa8ab7f86b223268b700bc67d15bb8aa/lib/incline/extensions/string.rb#L13-L18 | train |
BDMADE/signup | app/helpers/signup/users_helper.rb | Signup.UsersHelper.remember | def remember(user)
user.remember
cookies.permanent.signed[:user_id] = user.id
cookies.permanent[:remember_token] = user.remember_token
end | ruby | def remember(user)
user.remember
cookies.permanent.signed[:user_id] = user.id
cookies.permanent[:remember_token] = user.remember_token
end | [
"def",
"remember",
"(",
"user",
")",
"user",
".",
"remember",
"cookies",
".",
"permanent",
".",
"signed",
"[",
":user_id",
"]",
"=",
"user",
".",
"id",
"cookies",
".",
"permanent",
"[",
":remember_token",
"]",
"=",
"user",
".",
"remember_token",
"end"
] | Remembers a user in a persistent session. | [
"Remembers",
"a",
"user",
"in",
"a",
"persistent",
"session",
"."
] | 59a4b9a2d0ab54eac853193d9f4ac4a2dbf3f8e0 | https://github.com/BDMADE/signup/blob/59a4b9a2d0ab54eac853193d9f4ac4a2dbf3f8e0/app/helpers/signup/users_helper.rb#L9-L13 | train |
BDMADE/signup | app/helpers/signup/users_helper.rb | Signup.UsersHelper.current_user | def current_user
if (user_id = session[:user_id])
@current_user ||= User.find_by(id: user_id)
elsif (user_id = cookies.signed[:user_id])
user = User.find_by(id: user_id)
if user && user.authenticated?(cookies[:remember_token])
log_in user
@current_user = user
end
end
end | ruby | def current_user
if (user_id = session[:user_id])
@current_user ||= User.find_by(id: user_id)
elsif (user_id = cookies.signed[:user_id])
user = User.find_by(id: user_id)
if user && user.authenticated?(cookies[:remember_token])
log_in user
@current_user = user
end
end
end | [
"def",
"current_user",
"if",
"(",
"user_id",
"=",
"session",
"[",
":user_id",
"]",
")",
"@current_user",
"||=",
"User",
".",
"find_by",
"(",
"id",
":",
"user_id",
")",
"elsif",
"(",
"user_id",
"=",
"cookies",
".",
"signed",
"[",
":user_id",
"]",
")",
"user",
"=",
"User",
".",
"find_by",
"(",
"id",
":",
"user_id",
")",
"if",
"user",
"&&",
"user",
".",
"authenticated?",
"(",
"cookies",
"[",
":remember_token",
"]",
")",
"log_in",
"user",
"@current_user",
"=",
"user",
"end",
"end",
"end"
] | Returns the user corresponding to the remember token cookie. | [
"Returns",
"the",
"user",
"corresponding",
"to",
"the",
"remember",
"token",
"cookie",
"."
] | 59a4b9a2d0ab54eac853193d9f4ac4a2dbf3f8e0 | https://github.com/BDMADE/signup/blob/59a4b9a2d0ab54eac853193d9f4ac4a2dbf3f8e0/app/helpers/signup/users_helper.rb#L16-L26 | train |
RJMetrics/RJMetrics-ruby | lib/rjmetrics-client/client.rb | RJMetrics.Client.makeAuthAPICall | def makeAuthAPICall(url = API_BASE)
request_url = "#{url}/client/#{@client_id}/authenticate?apikey=#{@api_key}"
begin
response = RestClient.get(request_url)
return response
rescue RestClient::Exception => error
begin
response = JSON.parse(error.response)
unless response
raise InvalidRequestException, "The Import API returned: #{error.http_code} #{error.message}"
end
raise InvalidRequestException,
"The Import API returned: #{response['code']} #{response['message']}. Reasons: #{response['reasons']}"
rescue JSON::ParserError, TypeError => json_parse_error
raise InvalidResponseException,
"RestClientError: #{error.class}\n Message: #{error.message}\n Response Code: #{error.http_code}\n Full Response: #{error.response}"
end
end
end | ruby | def makeAuthAPICall(url = API_BASE)
request_url = "#{url}/client/#{@client_id}/authenticate?apikey=#{@api_key}"
begin
response = RestClient.get(request_url)
return response
rescue RestClient::Exception => error
begin
response = JSON.parse(error.response)
unless response
raise InvalidRequestException, "The Import API returned: #{error.http_code} #{error.message}"
end
raise InvalidRequestException,
"The Import API returned: #{response['code']} #{response['message']}. Reasons: #{response['reasons']}"
rescue JSON::ParserError, TypeError => json_parse_error
raise InvalidResponseException,
"RestClientError: #{error.class}\n Message: #{error.message}\n Response Code: #{error.http_code}\n Full Response: #{error.response}"
end
end
end | [
"def",
"makeAuthAPICall",
"(",
"url",
"=",
"API_BASE",
")",
"request_url",
"=",
"\"#{url}/client/#{@client_id}/authenticate?apikey=#{@api_key}\"",
"begin",
"response",
"=",
"RestClient",
".",
"get",
"(",
"request_url",
")",
"return",
"response",
"rescue",
"RestClient",
"::",
"Exception",
"=>",
"error",
"begin",
"response",
"=",
"JSON",
".",
"parse",
"(",
"error",
".",
"response",
")",
"unless",
"response",
"raise",
"InvalidRequestException",
",",
"\"The Import API returned: #{error.http_code} #{error.message}\"",
"end",
"raise",
"InvalidRequestException",
",",
"\"The Import API returned: #{response['code']} #{response['message']}. Reasons: #{response['reasons']}\"",
"rescue",
"JSON",
"::",
"ParserError",
",",
"TypeError",
"=>",
"json_parse_error",
"raise",
"InvalidResponseException",
",",
"\"RestClientError: #{error.class}\\n Message: #{error.message}\\n Response Code: #{error.http_code}\\n Full Response: #{error.response}\"",
"end",
"end",
"end"
] | Authenticates with the RJMetrics Data Import API | [
"Authenticates",
"with",
"the",
"RJMetrics",
"Data",
"Import",
"API"
] | f09d014af873656e2deb049a4975428afabdf088 | https://github.com/RJMetrics/RJMetrics-ruby/blob/f09d014af873656e2deb049a4975428afabdf088/lib/rjmetrics-client/client.rb#L94-L114 | train |
devnull-tools/yummi | lib/yummi/table.rb | Yummi.Table.column | def column(index)
index = parse_index(index)
columns = []
@data.each do |row|
columns << row_to_array(row)[index].value
end
columns
end | ruby | def column(index)
index = parse_index(index)
columns = []
@data.each do |row|
columns << row_to_array(row)[index].value
end
columns
end | [
"def",
"column",
"(",
"index",
")",
"index",
"=",
"parse_index",
"(",
"index",
")",
"columns",
"=",
"[",
"]",
"@data",
".",
"each",
"do",
"|",
"row",
"|",
"columns",
"<<",
"row_to_array",
"(",
"row",
")",
"[",
"index",
"]",
".",
"value",
"end",
"columns",
"end"
] | Retrieves the column at the given index. Aliases can be used | [
"Retrieves",
"the",
"column",
"at",
"the",
"given",
"index",
".",
"Aliases",
"can",
"be",
"used"
] | b31cc1ef9a9f4ca1c22e0b77a84a1995bde5c2df | https://github.com/devnull-tools/yummi/blob/b31cc1ef9a9f4ca1c22e0b77a84a1995bde5c2df/lib/yummi/table.rb#L174-L181 | train |
devnull-tools/yummi | lib/yummi/table.rb | Yummi.Table.header= | def header=(header)
header = [header] unless header.respond_to? :each
@header = normalize(header)
@aliases = header.map do |n|
n.downcase.gsub(' ', '_').gsub("\n", '_').to_sym
end if @aliases.empty?
end | ruby | def header=(header)
header = [header] unless header.respond_to? :each
@header = normalize(header)
@aliases = header.map do |n|
n.downcase.gsub(' ', '_').gsub("\n", '_').to_sym
end if @aliases.empty?
end | [
"def",
"header",
"=",
"(",
"header",
")",
"header",
"=",
"[",
"header",
"]",
"unless",
"header",
".",
"respond_to?",
":each",
"@header",
"=",
"normalize",
"(",
"header",
")",
"@aliases",
"=",
"header",
".",
"map",
"do",
"|",
"n",
"|",
"n",
".",
"downcase",
".",
"gsub",
"(",
"' '",
",",
"'_'",
")",
".",
"gsub",
"(",
"\"\\n\"",
",",
"'_'",
")",
".",
"to_sym",
"end",
"if",
"@aliases",
".",
"empty?",
"end"
] | Sets the table header. If no aliases are defined, they will be defined as the texts
in lowercase with line breaks and spaces replaced by underscores.
Defining headers also limits the printed column to only columns that has a header
(even if it is empty).
=== Args
+header+::
Array containing the texts for displaying the header. Line breaks are supported
=== Examples
table.header = ['Name', 'Email', 'Work Phone', "Home\nPhone"]
This will create the following aliases: :key, :email, :work_phone and :home_phone | [
"Sets",
"the",
"table",
"header",
".",
"If",
"no",
"aliases",
"are",
"defined",
"they",
"will",
"be",
"defined",
"as",
"the",
"texts",
"in",
"lowercase",
"with",
"line",
"breaks",
"and",
"spaces",
"replaced",
"by",
"underscores",
"."
] | b31cc1ef9a9f4ca1c22e0b77a84a1995bde5c2df | https://github.com/devnull-tools/yummi/blob/b31cc1ef9a9f4ca1c22e0b77a84a1995bde5c2df/lib/yummi/table.rb#L201-L207 | train |
devnull-tools/yummi | lib/yummi/table.rb | Yummi.Table.colorize | def colorize(indexes, params = {}, &block)
[*indexes].each do |index|
index = parse_index(index)
if index
obj = extract_component(params, &block)
component[:colorizers][index] = obj
else
colorize_null params, &block
end
end
end | ruby | def colorize(indexes, params = {}, &block)
[*indexes].each do |index|
index = parse_index(index)
if index
obj = extract_component(params, &block)
component[:colorizers][index] = obj
else
colorize_null params, &block
end
end
end | [
"def",
"colorize",
"(",
"indexes",
",",
"params",
"=",
"{",
"}",
",",
"&",
"block",
")",
"[",
"*",
"indexes",
"]",
".",
"each",
"do",
"|",
"index",
"|",
"index",
"=",
"parse_index",
"(",
"index",
")",
"if",
"index",
"obj",
"=",
"extract_component",
"(",
"params",
",",
"&",
"block",
")",
"component",
"[",
":colorizers",
"]",
"[",
"index",
"]",
"=",
"obj",
"else",
"colorize_null",
"params",
",",
"&",
"block",
"end",
"end",
"end"
] | Sets a component to colorize a column.
The component must respond to +call+ with the column value (or row if used with
#using_row) as the arguments and return a color or +nil+ if default color should be
used. A block can also be used.
=== Args
+indexes+::
The column indexes or its aliases
+params+::
A hash with params in case a block is not given:
- :using defines the component to use
- :with defines the color to use (to use the same color for all columns)
=== Example
table.colorize :description, :with => :magenta
table.colorize([:value, :total]) { |value| :red if value < 0 } | [
"Sets",
"a",
"component",
"to",
"colorize",
"a",
"column",
"."
] | b31cc1ef9a9f4ca1c22e0b77a84a1995bde5c2df | https://github.com/devnull-tools/yummi/blob/b31cc1ef9a9f4ca1c22e0b77a84a1995bde5c2df/lib/yummi/table.rb#L283-L293 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.