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 |
---|---|---|---|---|---|---|---|---|---|---|---|
sanichi/icu_tournament | lib/icu_tournament/tournament.rb | ICU.Tournament.check_dates | def check_dates
raise "start date (#{start}) is after end date (#{finish})" if @start && @finish && @start > @finish
if @round_dates.size > 0
raise "the number of round dates (#{@round_dates.size}) does not match the number of rounds (#{@rounds})" unless @round_dates.size == @rounds
raise "the date of the first round (#{@round_dates[0]}) does not match the start (#{@start}) of the tournament" if @start && @start != @round_dates[0]
raise "the date of the last round (#{@round_dates[-1]}) does not match the end (#{@finish}) of the tournament" if @finish && @finish != @round_dates[-1]
(2..@round_dates.size).to_a.each do |r|
#puts "#{@round_dates[r-2]} => #{@round_dates[r-1]}"
raise "the date of round #{r-1} (#{@round_dates[r-2]}) is after the date of round #{r} (#{@round_dates[r-1]}) of the tournament" if @round_dates[r-2] > @round_dates[r-1]
end
@finish = @round_dates[-1] unless @finish
end
end | ruby | def check_dates
raise "start date (#{start}) is after end date (#{finish})" if @start && @finish && @start > @finish
if @round_dates.size > 0
raise "the number of round dates (#{@round_dates.size}) does not match the number of rounds (#{@rounds})" unless @round_dates.size == @rounds
raise "the date of the first round (#{@round_dates[0]}) does not match the start (#{@start}) of the tournament" if @start && @start != @round_dates[0]
raise "the date of the last round (#{@round_dates[-1]}) does not match the end (#{@finish}) of the tournament" if @finish && @finish != @round_dates[-1]
(2..@round_dates.size).to_a.each do |r|
#puts "#{@round_dates[r-2]} => #{@round_dates[r-1]}"
raise "the date of round #{r-1} (#{@round_dates[r-2]}) is after the date of round #{r} (#{@round_dates[r-1]}) of the tournament" if @round_dates[r-2] > @round_dates[r-1]
end
@finish = @round_dates[-1] unless @finish
end
end | [
"def",
"check_dates",
"raise",
"\"start date (#{start}) is after end date (#{finish})\"",
"if",
"@start",
"&&",
"@finish",
"&&",
"@start",
">",
"@finish",
"if",
"@round_dates",
".",
"size",
">",
"0",
"raise",
"\"the number of round dates (#{@round_dates.size}) does not match the number of rounds (#{@rounds})\"",
"unless",
"@round_dates",
".",
"size",
"==",
"@rounds",
"raise",
"\"the date of the first round (#{@round_dates[0]}) does not match the start (#{@start}) of the tournament\"",
"if",
"@start",
"&&",
"@start",
"!=",
"@round_dates",
"[",
"0",
"]",
"raise",
"\"the date of the last round (#{@round_dates[-1]}) does not match the end (#{@finish}) of the tournament\"",
"if",
"@finish",
"&&",
"@finish",
"!=",
"@round_dates",
"[",
"-",
"1",
"]",
"(",
"2",
"..",
"@round_dates",
".",
"size",
")",
".",
"to_a",
".",
"each",
"do",
"|",
"r",
"|",
"#puts \"#{@round_dates[r-2]} => #{@round_dates[r-1]}\"",
"raise",
"\"the date of round #{r-1} (#{@round_dates[r-2]}) is after the date of round #{r} (#{@round_dates[r-1]}) of the tournament\"",
"if",
"@round_dates",
"[",
"r",
"-",
"2",
"]",
">",
"@round_dates",
"[",
"r",
"-",
"1",
"]",
"end",
"@finish",
"=",
"@round_dates",
"[",
"-",
"1",
"]",
"unless",
"@finish",
"end",
"end"
] | Check dates are consistent. | [
"Check",
"dates",
"are",
"consistent",
"."
] | badd2940189feaeb9f0edb4b4e07ff6b2548bd3d | https://github.com/sanichi/icu_tournament/blob/badd2940189feaeb9f0edb4b4e07ff6b2548bd3d/lib/icu_tournament/tournament.rb#L495-L507 | train |
sanichi/icu_tournament | lib/icu_tournament/tournament.rb | ICU.Tournament.check_type | def check_type(type)
if type.respond_to?(:validate!)
type.validate!(self)
elsif klass = self.class.factory(type.to_s)
klass.new.validate!(self)
else
raise "invalid type supplied for validation check"
end
end | ruby | def check_type(type)
if type.respond_to?(:validate!)
type.validate!(self)
elsif klass = self.class.factory(type.to_s)
klass.new.validate!(self)
else
raise "invalid type supplied for validation check"
end
end | [
"def",
"check_type",
"(",
"type",
")",
"if",
"type",
".",
"respond_to?",
"(",
":validate!",
")",
"type",
".",
"validate!",
"(",
"self",
")",
"elsif",
"klass",
"=",
"self",
".",
"class",
".",
"factory",
"(",
"type",
".",
"to_s",
")",
"klass",
".",
"new",
".",
"validate!",
"(",
"self",
")",
"else",
"raise",
"\"invalid type supplied for validation check\"",
"end",
"end"
] | Validate against a specific type. | [
"Validate",
"against",
"a",
"specific",
"type",
"."
] | badd2940189feaeb9f0edb4b4e07ff6b2548bd3d | https://github.com/sanichi/icu_tournament/blob/badd2940189feaeb9f0edb4b4e07ff6b2548bd3d/lib/icu_tournament/tournament.rb#L555-L563 | train |
sanichi/icu_tournament | lib/icu_tournament/tournament.rb | ICU.Tournament.tie_break_score | def tie_break_score(hash, method, player, rounds)
case method
when :score then player.points
when :wins then player.results.inject(0) { |t,r| t + (r.opponent && r.score == 'W' ? 1 : 0) }
when :blacks then player.results.inject(0) { |t,r| t + (r.opponent && r.colour == 'B' ? 1 : 0) }
when :buchholz then player.results.inject(0.0) { |t,r| t + (r.opponent ? hash[:opp_score][r.opponent] : 0.0) }
when :neustadtl then player.results.inject(0.0) { |t,r| t + (r.opponent ? hash[:opp_score][r.opponent] * r.points : 0.0) }
when :opp_score then player.results.inject(0.0) { |t,r| t + (r.opponent ? r.points : 0.5) } + (rounds - player.results.size) * 0.5
when :progressive then (1..rounds).inject(0.0) { |t,n| r = player.find_result(n); s = r ? r.points : 0.0; t + s * (rounds + 1 - n) }
when :ratings then player.results.inject(0) { |t,r| t + (r.opponent && (@player[r.opponent].fide_rating || @player[r.opponent].rating) ? (@player[r.opponent].fide_rating || @player[r.opponent].rating) : 0) }
when :harkness, :modified_median
scores = player.results.map{ |r| r.opponent ? hash[:opp_score][r.opponent] : 0.0 }.sort
1.upto(rounds - player.results.size) { scores << 0.0 }
half = rounds / 2.0
times = rounds >= 9 ? 2 : 1
if method == :harkness || player.points == half
1.upto(times) { scores.shift; scores.pop }
else
1.upto(times) { scores.send(player.points > half ? :shift : :pop) }
end
scores.inject(0.0) { |t,s| t + s }
else player.name
end
end | ruby | def tie_break_score(hash, method, player, rounds)
case method
when :score then player.points
when :wins then player.results.inject(0) { |t,r| t + (r.opponent && r.score == 'W' ? 1 : 0) }
when :blacks then player.results.inject(0) { |t,r| t + (r.opponent && r.colour == 'B' ? 1 : 0) }
when :buchholz then player.results.inject(0.0) { |t,r| t + (r.opponent ? hash[:opp_score][r.opponent] : 0.0) }
when :neustadtl then player.results.inject(0.0) { |t,r| t + (r.opponent ? hash[:opp_score][r.opponent] * r.points : 0.0) }
when :opp_score then player.results.inject(0.0) { |t,r| t + (r.opponent ? r.points : 0.5) } + (rounds - player.results.size) * 0.5
when :progressive then (1..rounds).inject(0.0) { |t,n| r = player.find_result(n); s = r ? r.points : 0.0; t + s * (rounds + 1 - n) }
when :ratings then player.results.inject(0) { |t,r| t + (r.opponent && (@player[r.opponent].fide_rating || @player[r.opponent].rating) ? (@player[r.opponent].fide_rating || @player[r.opponent].rating) : 0) }
when :harkness, :modified_median
scores = player.results.map{ |r| r.opponent ? hash[:opp_score][r.opponent] : 0.0 }.sort
1.upto(rounds - player.results.size) { scores << 0.0 }
half = rounds / 2.0
times = rounds >= 9 ? 2 : 1
if method == :harkness || player.points == half
1.upto(times) { scores.shift; scores.pop }
else
1.upto(times) { scores.send(player.points > half ? :shift : :pop) }
end
scores.inject(0.0) { |t,s| t + s }
else player.name
end
end | [
"def",
"tie_break_score",
"(",
"hash",
",",
"method",
",",
"player",
",",
"rounds",
")",
"case",
"method",
"when",
":score",
"then",
"player",
".",
"points",
"when",
":wins",
"then",
"player",
".",
"results",
".",
"inject",
"(",
"0",
")",
"{",
"|",
"t",
",",
"r",
"|",
"t",
"+",
"(",
"r",
".",
"opponent",
"&&",
"r",
".",
"score",
"==",
"'W'",
"?",
"1",
":",
"0",
")",
"}",
"when",
":blacks",
"then",
"player",
".",
"results",
".",
"inject",
"(",
"0",
")",
"{",
"|",
"t",
",",
"r",
"|",
"t",
"+",
"(",
"r",
".",
"opponent",
"&&",
"r",
".",
"colour",
"==",
"'B'",
"?",
"1",
":",
"0",
")",
"}",
"when",
":buchholz",
"then",
"player",
".",
"results",
".",
"inject",
"(",
"0.0",
")",
"{",
"|",
"t",
",",
"r",
"|",
"t",
"+",
"(",
"r",
".",
"opponent",
"?",
"hash",
"[",
":opp_score",
"]",
"[",
"r",
".",
"opponent",
"]",
":",
"0.0",
")",
"}",
"when",
":neustadtl",
"then",
"player",
".",
"results",
".",
"inject",
"(",
"0.0",
")",
"{",
"|",
"t",
",",
"r",
"|",
"t",
"+",
"(",
"r",
".",
"opponent",
"?",
"hash",
"[",
":opp_score",
"]",
"[",
"r",
".",
"opponent",
"]",
"*",
"r",
".",
"points",
":",
"0.0",
")",
"}",
"when",
":opp_score",
"then",
"player",
".",
"results",
".",
"inject",
"(",
"0.0",
")",
"{",
"|",
"t",
",",
"r",
"|",
"t",
"+",
"(",
"r",
".",
"opponent",
"?",
"r",
".",
"points",
":",
"0.5",
")",
"}",
"+",
"(",
"rounds",
"-",
"player",
".",
"results",
".",
"size",
")",
"*",
"0.5",
"when",
":progressive",
"then",
"(",
"1",
"..",
"rounds",
")",
".",
"inject",
"(",
"0.0",
")",
"{",
"|",
"t",
",",
"n",
"|",
"r",
"=",
"player",
".",
"find_result",
"(",
"n",
")",
";",
"s",
"=",
"r",
"?",
"r",
".",
"points",
":",
"0.0",
";",
"t",
"+",
"s",
"*",
"(",
"rounds",
"+",
"1",
"-",
"n",
")",
"}",
"when",
":ratings",
"then",
"player",
".",
"results",
".",
"inject",
"(",
"0",
")",
"{",
"|",
"t",
",",
"r",
"|",
"t",
"+",
"(",
"r",
".",
"opponent",
"&&",
"(",
"@player",
"[",
"r",
".",
"opponent",
"]",
".",
"fide_rating",
"||",
"@player",
"[",
"r",
".",
"opponent",
"]",
".",
"rating",
")",
"?",
"(",
"@player",
"[",
"r",
".",
"opponent",
"]",
".",
"fide_rating",
"||",
"@player",
"[",
"r",
".",
"opponent",
"]",
".",
"rating",
")",
":",
"0",
")",
"}",
"when",
":harkness",
",",
":modified_median",
"scores",
"=",
"player",
".",
"results",
".",
"map",
"{",
"|",
"r",
"|",
"r",
".",
"opponent",
"?",
"hash",
"[",
":opp_score",
"]",
"[",
"r",
".",
"opponent",
"]",
":",
"0.0",
"}",
".",
"sort",
"1",
".",
"upto",
"(",
"rounds",
"-",
"player",
".",
"results",
".",
"size",
")",
"{",
"scores",
"<<",
"0.0",
"}",
"half",
"=",
"rounds",
"/",
"2.0",
"times",
"=",
"rounds",
">=",
"9",
"?",
"2",
":",
"1",
"if",
"method",
"==",
":harkness",
"||",
"player",
".",
"points",
"==",
"half",
"1",
".",
"upto",
"(",
"times",
")",
"{",
"scores",
".",
"shift",
";",
"scores",
".",
"pop",
"}",
"else",
"1",
".",
"upto",
"(",
"times",
")",
"{",
"scores",
".",
"send",
"(",
"player",
".",
"points",
">",
"half",
"?",
":shift",
":",
":pop",
")",
"}",
"end",
"scores",
".",
"inject",
"(",
"0.0",
")",
"{",
"|",
"t",
",",
"s",
"|",
"t",
"+",
"s",
"}",
"else",
"player",
".",
"name",
"end",
"end"
] | Return a tie break score for a given player and a given tie break method. | [
"Return",
"a",
"tie",
"break",
"score",
"for",
"a",
"given",
"player",
"and",
"a",
"given",
"tie",
"break",
"method",
"."
] | badd2940189feaeb9f0edb4b4e07ff6b2548bd3d | https://github.com/sanichi/icu_tournament/blob/badd2940189feaeb9f0edb4b4e07ff6b2548bd3d/lib/icu_tournament/tournament.rb#L611-L634 | train |
spikegrobstein/capnotify | lib/capnotify/plugin.rb | Capnotify.Plugin.deployed_by | def deployed_by
username = nil
scm = fetch(:scm, nil)
if scm
if scm.to_sym == :git
username = `git config user.name`.chomp
username = nil if $? != 0 || username.strip == ''
end
end
username || `whoami`.chomp
end | ruby | def deployed_by
username = nil
scm = fetch(:scm, nil)
if scm
if scm.to_sym == :git
username = `git config user.name`.chomp
username = nil if $? != 0 || username.strip == ''
end
end
username || `whoami`.chomp
end | [
"def",
"deployed_by",
"username",
"=",
"nil",
"scm",
"=",
"fetch",
"(",
":scm",
",",
"nil",
")",
"if",
"scm",
"if",
"scm",
".",
"to_sym",
"==",
":git",
"username",
"=",
"`",
"`",
".",
"chomp",
"username",
"=",
"nil",
"if",
"$?",
"!=",
"0",
"||",
"username",
".",
"strip",
"==",
"''",
"end",
"end",
"username",
"||",
"`",
"`",
".",
"chomp",
"end"
] | get the name of the deploying user
currently this only supports git.
if reading the git user.name, fall back on `whoami` | [
"get",
"the",
"name",
"of",
"the",
"deploying",
"user",
"currently",
"this",
"only",
"supports",
"git",
".",
"if",
"reading",
"the",
"git",
"user",
".",
"name",
"fall",
"back",
"on",
"whoami"
] | b21ea876ae2a04e8090206a687436565051f0e08 | https://github.com/spikegrobstein/capnotify/blob/b21ea876ae2a04e8090206a687436565051f0e08/lib/capnotify/plugin.rb#L33-L46 | train |
spikegrobstein/capnotify | lib/capnotify/plugin.rb | Capnotify.Plugin.unload_plugin | def unload_plugin(name)
p = get_plugin(name)
p.unload if p.respond_to?(:unload)
Capistrano.remove_plugin(name)
end | ruby | def unload_plugin(name)
p = get_plugin(name)
p.unload if p.respond_to?(:unload)
Capistrano.remove_plugin(name)
end | [
"def",
"unload_plugin",
"(",
"name",
")",
"p",
"=",
"get_plugin",
"(",
"name",
")",
"p",
".",
"unload",
"if",
"p",
".",
"respond_to?",
"(",
":unload",
")",
"Capistrano",
".",
"remove_plugin",
"(",
"name",
")",
"end"
] | given a plugin name as a symbol, unload the capnotify plugin
this will also unload any kind of capistrano plugin
if the plugin supports the unload method, it will be called. | [
"given",
"a",
"plugin",
"name",
"as",
"a",
"symbol",
"unload",
"the",
"capnotify",
"plugin",
"this",
"will",
"also",
"unload",
"any",
"kind",
"of",
"capistrano",
"plugin",
"if",
"the",
"plugin",
"supports",
"the",
"unload",
"method",
"it",
"will",
"be",
"called",
"."
] | b21ea876ae2a04e8090206a687436565051f0e08 | https://github.com/spikegrobstein/capnotify/blob/b21ea876ae2a04e8090206a687436565051f0e08/lib/capnotify/plugin.rb#L71-L76 | train |
spikegrobstein/capnotify | lib/capnotify/plugin.rb | Capnotify.Plugin.get_plugin | def get_plugin(name)
raise "Unknown plugin: #{ name }" unless Capistrano::EXTENSIONS.keys.include?(name)
self.send(name)
end | ruby | def get_plugin(name)
raise "Unknown plugin: #{ name }" unless Capistrano::EXTENSIONS.keys.include?(name)
self.send(name)
end | [
"def",
"get_plugin",
"(",
"name",
")",
"raise",
"\"Unknown plugin: #{ name }\"",
"unless",
"Capistrano",
"::",
"EXTENSIONS",
".",
"keys",
".",
"include?",
"(",
"name",
")",
"self",
".",
"send",
"(",
"name",
")",
"end"
] | given a plugin name, return the plugin. | [
"given",
"a",
"plugin",
"name",
"return",
"the",
"plugin",
"."
] | b21ea876ae2a04e8090206a687436565051f0e08 | https://github.com/spikegrobstein/capnotify/blob/b21ea876ae2a04e8090206a687436565051f0e08/lib/capnotify/plugin.rb#L79-L82 | train |
spikegrobstein/capnotify | lib/capnotify/plugin.rb | Capnotify.Plugin.build_template | def build_template(template_path)
# FIXME: this is called every time build_template is called.
# although this is idepodent, it's got room for optimization
self.build_components!
ERB.new( File.open( template_path ).read, nil, '<>' ).result(self.binding)
end | ruby | def build_template(template_path)
# FIXME: this is called every time build_template is called.
# although this is idepodent, it's got room for optimization
self.build_components!
ERB.new( File.open( template_path ).read, nil, '<>' ).result(self.binding)
end | [
"def",
"build_template",
"(",
"template_path",
")",
"# FIXME: this is called every time build_template is called.",
"# although this is idepodent, it's got room for optimization",
"self",
".",
"build_components!",
"ERB",
".",
"new",
"(",
"File",
".",
"open",
"(",
"template_path",
")",
".",
"read",
",",
"nil",
",",
"'<>'",
")",
".",
"result",
"(",
"self",
".",
"binding",
")",
"end"
] | given a path to an ERB template, process it with the current binding and return the output. | [
"given",
"a",
"path",
"to",
"an",
"ERB",
"template",
"process",
"it",
"with",
"the",
"current",
"binding",
"and",
"return",
"the",
"output",
"."
] | b21ea876ae2a04e8090206a687436565051f0e08 | https://github.com/spikegrobstein/capnotify/blob/b21ea876ae2a04e8090206a687436565051f0e08/lib/capnotify/plugin.rb#L93-L99 | train |
spikegrobstein/capnotify | lib/capnotify/plugin.rb | Capnotify.Plugin.component | def component(name)
components.each { |c| return c if c.name == name.to_sym }
return nil
end | ruby | def component(name)
components.each { |c| return c if c.name == name.to_sym }
return nil
end | [
"def",
"component",
"(",
"name",
")",
"components",
".",
"each",
"{",
"|",
"c",
"|",
"return",
"c",
"if",
"c",
".",
"name",
"==",
"name",
".",
"to_sym",
"}",
"return",
"nil",
"end"
] | fetch a component given the name
this is most useful for getting a component directly if you want to make modificatins to it | [
"fetch",
"a",
"component",
"given",
"the",
"name",
"this",
"is",
"most",
"useful",
"for",
"getting",
"a",
"component",
"directly",
"if",
"you",
"want",
"to",
"make",
"modificatins",
"to",
"it"
] | b21ea876ae2a04e8090206a687436565051f0e08 | https://github.com/spikegrobstein/capnotify/blob/b21ea876ae2a04e8090206a687436565051f0e08/lib/capnotify/plugin.rb#L112-L115 | train |
spikegrobstein/capnotify | lib/capnotify/plugin.rb | Capnotify.Plugin.insert_component_before | def insert_component_before(name, component)
# iterate over all components, find the component with the given name
# once found, insert the given component at that location and return
components.each_with_index do |c, i|
if c.name == name
components.insert(i, component)
return
end
end
components << component
end | ruby | def insert_component_before(name, component)
# iterate over all components, find the component with the given name
# once found, insert the given component at that location and return
components.each_with_index do |c, i|
if c.name == name
components.insert(i, component)
return
end
end
components << component
end | [
"def",
"insert_component_before",
"(",
"name",
",",
"component",
")",
"# iterate over all components, find the component with the given name",
"# once found, insert the given component at that location and return",
"components",
".",
"each_with_index",
"do",
"|",
"c",
",",
"i",
"|",
"if",
"c",
".",
"name",
"==",
"name",
"components",
".",
"insert",
"(",
"i",
",",
"component",
")",
"return",
"end",
"end",
"components",
"<<",
"component",
"end"
] | insert the given component before the component with `name`
if no component is found with that name, the component will be inserted at the end | [
"insert",
"the",
"given",
"component",
"before",
"the",
"component",
"with",
"name",
"if",
"no",
"component",
"is",
"found",
"with",
"that",
"name",
"the",
"component",
"will",
"be",
"inserted",
"at",
"the",
"end"
] | b21ea876ae2a04e8090206a687436565051f0e08 | https://github.com/spikegrobstein/capnotify/blob/b21ea876ae2a04e8090206a687436565051f0e08/lib/capnotify/plugin.rb#L119-L130 | train |
spikegrobstein/capnotify | lib/capnotify/plugin.rb | Capnotify.Plugin.insert_component_after | def insert_component_after(name, component)
# iterate over all components, find the component with the given name
# once found, insert the given component at the following location and return
components.each_with_index do |c, i|
if c.name == name
components.insert(i + 1, component)
return
end
end
components << component
end | ruby | def insert_component_after(name, component)
# iterate over all components, find the component with the given name
# once found, insert the given component at the following location and return
components.each_with_index do |c, i|
if c.name == name
components.insert(i + 1, component)
return
end
end
components << component
end | [
"def",
"insert_component_after",
"(",
"name",
",",
"component",
")",
"# iterate over all components, find the component with the given name",
"# once found, insert the given component at the following location and return",
"components",
".",
"each_with_index",
"do",
"|",
"c",
",",
"i",
"|",
"if",
"c",
".",
"name",
"==",
"name",
"components",
".",
"insert",
"(",
"i",
"+",
"1",
",",
"component",
")",
"return",
"end",
"end",
"components",
"<<",
"component",
"end"
] | insert the given component after the component with `name`
if no component is found with that name, the component will be inserted at the end | [
"insert",
"the",
"given",
"component",
"after",
"the",
"component",
"with",
"name",
"if",
"no",
"component",
"is",
"found",
"with",
"that",
"name",
"the",
"component",
"will",
"be",
"inserted",
"at",
"the",
"end"
] | b21ea876ae2a04e8090206a687436565051f0e08 | https://github.com/spikegrobstein/capnotify/blob/b21ea876ae2a04e8090206a687436565051f0e08/lib/capnotify/plugin.rb#L134-L145 | train |
ykpeng/networkr | lib/networkr/graphs/multigraph.rb | Networkr.MultiGraph.new_edge_key | def new_edge_key(u, v)
if @adj[u] && @adj[u][v]
keys = @adj[u][v]
key = keys.length
while keys.include?(key)
key += 1
end
return key
else
return 0
end
end | ruby | def new_edge_key(u, v)
if @adj[u] && @adj[u][v]
keys = @adj[u][v]
key = keys.length
while keys.include?(key)
key += 1
end
return key
else
return 0
end
end | [
"def",
"new_edge_key",
"(",
"u",
",",
"v",
")",
"if",
"@adj",
"[",
"u",
"]",
"&&",
"@adj",
"[",
"u",
"]",
"[",
"v",
"]",
"keys",
"=",
"@adj",
"[",
"u",
"]",
"[",
"v",
"]",
"key",
"=",
"keys",
".",
"length",
"while",
"keys",
".",
"include?",
"(",
"key",
")",
"key",
"+=",
"1",
"end",
"return",
"key",
"else",
"return",
"0",
"end",
"end"
] | returns an unused key for edges between nodes 'u' and 'v'.
The nodes 'u' and 'v' do not need to be already in the graph.
Notes
-----
The new key is the number of existing edges between 'u' and 'v', increased if necessary to ensure uniqueness. The first edge will have key 0, the second edge 1, etc. If an edge is removed, new keys may not be in this order.
Parameters
----------
u, v: nodes
Returns
-------
key: int | [
"returns",
"an",
"unused",
"key",
"for",
"edges",
"between",
"nodes",
"u",
"and",
"v",
"."
] | 8b3f9495b53a73735c1a73aa98c7327423377eb6 | https://github.com/ykpeng/networkr/blob/8b3f9495b53a73735c1a73aa98c7327423377eb6/lib/networkr/graphs/multigraph.rb#L28-L39 | train |
mpapis/gh_contributors | lib/gh_contributors/calculator.rb | GhContributors.Calculator.calculated_data | def calculated_data
@data ||= @raw_data.group_by { |contributor|
contributor['login']
}.map {|login, data|
log "user: #{login}"
[login, user_data(login, data)]
}.sort_by{|login, data|
[1000000/data['contributions'], login]
}
end | ruby | def calculated_data
@data ||= @raw_data.group_by { |contributor|
contributor['login']
}.map {|login, data|
log "user: #{login}"
[login, user_data(login, data)]
}.sort_by{|login, data|
[1000000/data['contributions'], login]
}
end | [
"def",
"calculated_data",
"@data",
"||=",
"@raw_data",
".",
"group_by",
"{",
"|",
"contributor",
"|",
"contributor",
"[",
"'login'",
"]",
"}",
".",
"map",
"{",
"|",
"login",
",",
"data",
"|",
"log",
"\"user: #{login}\"",
"[",
"login",
",",
"user_data",
"(",
"login",
",",
"data",
")",
"]",
"}",
".",
"sort_by",
"{",
"|",
"login",
",",
"data",
"|",
"[",
"1000000",
"/",
"data",
"[",
"'contributions'",
"]",
",",
"login",
"]",
"}",
"end"
] | group data, calculate contributions, sort by contributions | [
"group",
"data",
"calculate",
"contributions",
"sort",
"by",
"contributions"
] | 3d5c82acf697384a0f965f73b8d5be092022d4a8 | https://github.com/mpapis/gh_contributors/blob/3d5c82acf697384a0f965f73b8d5be092022d4a8/lib/gh_contributors/calculator.rb#L26-L35 | train |
caruby/scat | lib/scat/cache.rb | Scat.Cache.start | def start(redis)
logger.debug { "Scat is starting the Redis cache server..." }
unless system(REDIS_SERVER, REDIS_CONF) then
raise ScatError.new("Scat cannot start the Redis cache server.")
end
# Ping the server until loaded.
3.times do |n|
begin
redis.ping
logger.debug { "Scat started the Redis cache server." }
return redis
rescue
n < 2 ? sleep(0.5) : raise
end
end
end | ruby | def start(redis)
logger.debug { "Scat is starting the Redis cache server..." }
unless system(REDIS_SERVER, REDIS_CONF) then
raise ScatError.new("Scat cannot start the Redis cache server.")
end
# Ping the server until loaded.
3.times do |n|
begin
redis.ping
logger.debug { "Scat started the Redis cache server." }
return redis
rescue
n < 2 ? sleep(0.5) : raise
end
end
end | [
"def",
"start",
"(",
"redis",
")",
"logger",
".",
"debug",
"{",
"\"Scat is starting the Redis cache server...\"",
"}",
"unless",
"system",
"(",
"REDIS_SERVER",
",",
"REDIS_CONF",
")",
"then",
"raise",
"ScatError",
".",
"new",
"(",
"\"Scat cannot start the Redis cache server.\"",
")",
"end",
"# Ping the server until loaded. ",
"3",
".",
"times",
"do",
"|",
"n",
"|",
"begin",
"redis",
".",
"ping",
"logger",
".",
"debug",
"{",
"\"Scat started the Redis cache server.\"",
"}",
"return",
"redis",
"rescue",
"n",
"<",
"2",
"?",
"sleep",
"(",
"0.5",
")",
":",
"raise",
"end",
"end",
"end"
] | Starts the Redis server on the default Redis port.
@param [Redis] the Redis client
@raise [ScatError] if the server command could not be executed
@raise [Exception] if the server is not reachable | [
"Starts",
"the",
"Redis",
"server",
"on",
"the",
"default",
"Redis",
"port",
"."
] | 90291b317eb6b8ef8b0a4497622eadc15d3d9028 | https://github.com/caruby/scat/blob/90291b317eb6b8ef8b0a4497622eadc15d3d9028/lib/scat/cache.rb#L73-L88 | train |
cordawyn/redlander | lib/redlander/model.rb | Redlander.Model.query | def query(q, options = {}, &block)
query = Query::Results.new(q, options)
query.process(self, &block)
end | ruby | def query(q, options = {}, &block)
query = Query::Results.new(q, options)
query.process(self, &block)
end | [
"def",
"query",
"(",
"q",
",",
"options",
"=",
"{",
"}",
",",
"&",
"block",
")",
"query",
"=",
"Query",
"::",
"Results",
".",
"new",
"(",
"q",
",",
"options",
")",
"query",
".",
"process",
"(",
"self",
",",
"block",
")",
"end"
] | Query the model RDF graph using a query language
@param [String] q the text of the query
@param [Hash<Symbol => [String, URI]>] options options for the query
@option options [String] :language language of the query, one of:
- "sparql10" SPARQL 1.0 W3C RDF Query Language (default)
- "sparql" SPARQL 1.1 (DRAFT) Query and Update Languages
- "sparql11-query" SPARQL 1.1 (DRAFT) Query Language
- "sparql11-update" SPARQL 1.1 (DRAFT) Update Language
- "laqrs" LAQRS adds to Querying RDF in SPARQL
- "rdql" RDF Data Query Language (RDQL)
@option options [String] :language_uri URI of the query language, if applicable
@option options [String] :base_uri base URI of the query, if applicable
@return [void]
@note
The returned value is determined by the type of the query:
- [Boolean] for SPARQL ASK queries (ignores block, if given)
- [Redlander::Model] for SPARQL CONSTRUCT queries
if given a block, yields the constructed statements to it instead
- [Array<Hash>] for SPARQL SELECT queries
where hash values are Redlander::Node instances;
if given a block, yields each binding hash to it
- nil, if query fails
@raise [RedlandError] if fails to create a query | [
"Query",
"the",
"model",
"RDF",
"graph",
"using",
"a",
"query",
"language"
] | a5c84e15a7602c674606e531bda6a616b1237c44 | https://github.com/cordawyn/redlander/blob/a5c84e15a7602c674606e531bda6a616b1237c44/lib/redlander/model.rb#L116-L119 | train |
octoai/gem-octocore-cassandra | lib/octocore-cassandra/models/enterprise/funnels.rb | Octo.Funnel.populate_with_fake_data | def populate_with_fake_data(interval_days = 7)
if self.enterprise.fakedata?
today = Time.now.beginning_of_day
(today - interval_days.days).to(today, 24.hour).each do |ts|
Octo::FunnelData.new(
enterprise_id: self.enterprise_id,
funnel_slug: self.name_slug,
ts: ts,
value: fake_data(self.funnel.count)
).save!
end
end
end | ruby | def populate_with_fake_data(interval_days = 7)
if self.enterprise.fakedata?
today = Time.now.beginning_of_day
(today - interval_days.days).to(today, 24.hour).each do |ts|
Octo::FunnelData.new(
enterprise_id: self.enterprise_id,
funnel_slug: self.name_slug,
ts: ts,
value: fake_data(self.funnel.count)
).save!
end
end
end | [
"def",
"populate_with_fake_data",
"(",
"interval_days",
"=",
"7",
")",
"if",
"self",
".",
"enterprise",
".",
"fakedata?",
"today",
"=",
"Time",
".",
"now",
".",
"beginning_of_day",
"(",
"today",
"-",
"interval_days",
".",
"days",
")",
".",
"to",
"(",
"today",
",",
"24",
".",
"hour",
")",
".",
"each",
"do",
"|",
"ts",
"|",
"Octo",
"::",
"FunnelData",
".",
"new",
"(",
"enterprise_id",
":",
"self",
".",
"enterprise_id",
",",
"funnel_slug",
":",
"self",
".",
"name_slug",
",",
"ts",
":",
"ts",
",",
"value",
":",
"fake_data",
"(",
"self",
".",
"funnel",
".",
"count",
")",
")",
".",
"save!",
"end",
"end",
"end"
] | Populates a newly created funnel with some fake data
@param [Fixnum] days The number of days for which data to be faked | [
"Populates",
"a",
"newly",
"created",
"funnel",
"with",
"some",
"fake",
"data"
] | c0977dce5ba0eb174ff810f161aba151069935df | https://github.com/octoai/gem-octocore-cassandra/blob/c0977dce5ba0eb174ff810f161aba151069935df/lib/octocore-cassandra/models/enterprise/funnels.rb#L75-L87 | train |
octoai/gem-octocore-cassandra | lib/octocore-cassandra/models/enterprise/funnels.rb | Octo.Funnel.data | def data(ts = Time.now.floor)
args = {
enterprise_id: self.enterprise.id,
funnel_slug: self.name_slug,
ts: ts
}
res = Octo::FunnelData.where(args)
if res.count > 0
res.first
elsif self.enterprise.fakedata?
args.merge!({ value: fake_data(self.funnel.count) })
Octo::FunnelData.new(args).save!
end
end | ruby | def data(ts = Time.now.floor)
args = {
enterprise_id: self.enterprise.id,
funnel_slug: self.name_slug,
ts: ts
}
res = Octo::FunnelData.where(args)
if res.count > 0
res.first
elsif self.enterprise.fakedata?
args.merge!({ value: fake_data(self.funnel.count) })
Octo::FunnelData.new(args).save!
end
end | [
"def",
"data",
"(",
"ts",
"=",
"Time",
".",
"now",
".",
"floor",
")",
"args",
"=",
"{",
"enterprise_id",
":",
"self",
".",
"enterprise",
".",
"id",
",",
"funnel_slug",
":",
"self",
".",
"name_slug",
",",
"ts",
":",
"ts",
"}",
"res",
"=",
"Octo",
"::",
"FunnelData",
".",
"where",
"(",
"args",
")",
"if",
"res",
".",
"count",
">",
"0",
"res",
".",
"first",
"elsif",
"self",
".",
"enterprise",
".",
"fakedata?",
"args",
".",
"merge!",
"(",
"{",
"value",
":",
"fake_data",
"(",
"self",
".",
"funnel",
".",
"count",
")",
"}",
")",
"Octo",
"::",
"FunnelData",
".",
"new",
"(",
"args",
")",
".",
"save!",
"end",
"end"
] | Returns data for a funnel
@return [Octo::FunnelData] The Octo funnel data | [
"Returns",
"data",
"for",
"a",
"funnel"
] | c0977dce5ba0eb174ff810f161aba151069935df | https://github.com/octoai/gem-octocore-cassandra/blob/c0977dce5ba0eb174ff810f161aba151069935df/lib/octocore-cassandra/models/enterprise/funnels.rb#L91-L104 | train |
octoai/gem-octocore-cassandra | lib/octocore-cassandra/models/enterprise/funnels.rb | Octo.Funnel.fake_data | def fake_data(n)
fun = Array.new(n)
max_dropoff = 100/n
n.times do |i|
if i == 0
fun[i] = 100.0
else
fun[i] = fun[i-1] - rand(1..max_dropoff)
if fun[i] < 0
fun[i] = rand(0...fun[i].abs)
end
end
end
fun
end | ruby | def fake_data(n)
fun = Array.new(n)
max_dropoff = 100/n
n.times do |i|
if i == 0
fun[i] = 100.0
else
fun[i] = fun[i-1] - rand(1..max_dropoff)
if fun[i] < 0
fun[i] = rand(0...fun[i].abs)
end
end
end
fun
end | [
"def",
"fake_data",
"(",
"n",
")",
"fun",
"=",
"Array",
".",
"new",
"(",
"n",
")",
"max_dropoff",
"=",
"100",
"/",
"n",
"n",
".",
"times",
"do",
"|",
"i",
"|",
"if",
"i",
"==",
"0",
"fun",
"[",
"i",
"]",
"=",
"100.0",
"else",
"fun",
"[",
"i",
"]",
"=",
"fun",
"[",
"i",
"-",
"1",
"]",
"-",
"rand",
"(",
"1",
"..",
"max_dropoff",
")",
"if",
"fun",
"[",
"i",
"]",
"<",
"0",
"fun",
"[",
"i",
"]",
"=",
"rand",
"(",
"0",
"...",
"fun",
"[",
"i",
"]",
".",
"abs",
")",
"end",
"end",
"end",
"fun",
"end"
] | Generates fake data for funnel
@param [Fixnum] n The length of funnel
@return [Array] An array containing the funnel value | [
"Generates",
"fake",
"data",
"for",
"funnel"
] | c0977dce5ba0eb174ff810f161aba151069935df | https://github.com/octoai/gem-octocore-cassandra/blob/c0977dce5ba0eb174ff810f161aba151069935df/lib/octocore-cassandra/models/enterprise/funnels.rb#L111-L125 | train |
betaworks/slack-bot-manager | lib/slack-bot-manager/client/base.rb | SlackBotManager.Client.handle_error | def handle_error(err, data = nil)
case determine_error_type(err)
when :token_revoked
on_revoke(data)
when :rate_limited
on_rate_limit(data)
when :closed
on_close(data)
else
on_error(err, data)
end
end | ruby | def handle_error(err, data = nil)
case determine_error_type(err)
when :token_revoked
on_revoke(data)
when :rate_limited
on_rate_limit(data)
when :closed
on_close(data)
else
on_error(err, data)
end
end | [
"def",
"handle_error",
"(",
"err",
",",
"data",
"=",
"nil",
")",
"case",
"determine_error_type",
"(",
"err",
")",
"when",
":token_revoked",
"on_revoke",
"(",
"data",
")",
"when",
":rate_limited",
"on_rate_limit",
"(",
"data",
")",
"when",
":closed",
"on_close",
"(",
"data",
")",
"else",
"on_error",
"(",
"err",
",",
"data",
")",
"end",
"end"
] | Handle different error cases | [
"Handle",
"different",
"error",
"cases"
] | cb59bd1c80abd3ede0520017708891486f733e40 | https://github.com/betaworks/slack-bot-manager/blob/cb59bd1c80abd3ede0520017708891486f733e40/lib/slack-bot-manager/client/base.rb#L118-L129 | train |
fotonauts/activr | lib/activr/storage.rb | Activr.Storage.find_activity | def find_activity(activity_id)
activity_hash = self.driver.find_activity(activity_id)
if activity_hash
# run hook
self.run_hook(:did_find_activity, activity_hash)
# unserialize
Activr::Activity.from_hash(activity_hash)
else
nil
end
end | ruby | def find_activity(activity_id)
activity_hash = self.driver.find_activity(activity_id)
if activity_hash
# run hook
self.run_hook(:did_find_activity, activity_hash)
# unserialize
Activr::Activity.from_hash(activity_hash)
else
nil
end
end | [
"def",
"find_activity",
"(",
"activity_id",
")",
"activity_hash",
"=",
"self",
".",
"driver",
".",
"find_activity",
"(",
"activity_id",
")",
"if",
"activity_hash",
"# run hook",
"self",
".",
"run_hook",
"(",
":did_find_activity",
",",
"activity_hash",
")",
"# unserialize",
"Activr",
"::",
"Activity",
".",
"from_hash",
"(",
"activity_hash",
")",
"else",
"nil",
"end",
"end"
] | Find an activity
@param activity_id [Object] Activity id to find
@return [Activity, Nil] An activity instance or `nil` if not found | [
"Find",
"an",
"activity"
] | 92c071ad18a76d4130661da3ce47c1f0fb8ae913 | https://github.com/fotonauts/activr/blob/92c071ad18a76d4130661da3ce47c1f0fb8ae913/lib/activr/storage.rb#L76-L87 | train |
fotonauts/activr | lib/activr/storage.rb | Activr.Storage.find_activities | def find_activities(limit, options = { })
# default options
options = {
:skip => 0,
:before => nil,
:after => nil,
:entities => { },
:only => [ ],
:except => [ ],
}.merge(options)
options[:only] = [ options[:only] ] if (options[:only] && !options[:only].is_a?(Array))
# find
result = self.driver.find_activities(limit, options).map do |activity_hash|
# run hook
self.run_hook(:did_find_activity, activity_hash)
# unserialize
Activr::Activity.from_hash(activity_hash)
end
result
end | ruby | def find_activities(limit, options = { })
# default options
options = {
:skip => 0,
:before => nil,
:after => nil,
:entities => { },
:only => [ ],
:except => [ ],
}.merge(options)
options[:only] = [ options[:only] ] if (options[:only] && !options[:only].is_a?(Array))
# find
result = self.driver.find_activities(limit, options).map do |activity_hash|
# run hook
self.run_hook(:did_find_activity, activity_hash)
# unserialize
Activr::Activity.from_hash(activity_hash)
end
result
end | [
"def",
"find_activities",
"(",
"limit",
",",
"options",
"=",
"{",
"}",
")",
"# default options",
"options",
"=",
"{",
":skip",
"=>",
"0",
",",
":before",
"=>",
"nil",
",",
":after",
"=>",
"nil",
",",
":entities",
"=>",
"{",
"}",
",",
":only",
"=>",
"[",
"]",
",",
":except",
"=>",
"[",
"]",
",",
"}",
".",
"merge",
"(",
"options",
")",
"options",
"[",
":only",
"]",
"=",
"[",
"options",
"[",
":only",
"]",
"]",
"if",
"(",
"options",
"[",
":only",
"]",
"&&",
"!",
"options",
"[",
":only",
"]",
".",
"is_a?",
"(",
"Array",
")",
")",
"# find",
"result",
"=",
"self",
".",
"driver",
".",
"find_activities",
"(",
"limit",
",",
"options",
")",
".",
"map",
"do",
"|",
"activity_hash",
"|",
"# run hook",
"self",
".",
"run_hook",
"(",
":did_find_activity",
",",
"activity_hash",
")",
"# unserialize",
"Activr",
"::",
"Activity",
".",
"from_hash",
"(",
"activity_hash",
")",
"end",
"result",
"end"
] | Find latest activities
@note If you use others selectors then 'limit' argument and 'skip' option then you have to setup corresponding indexes in database.
@param limit [Integer] Max number of activities to find
@param options [Hash] Options hash
@option options [Integer] :skip Number of activities to skip (default: 0)
@option options [Time] :before Find activities generated before that datetime (excluding)
@option options [Time] :after Find activities generated after that datetime (excluding)
@option options [Hash{Sym=>String}] :entities Filter by entities values (empty means 'all values')
@option options [Array<Class>] :only Find only these activities
@option options [Array<Class>] :except Skip these activities
@return [Array<Activity>] An array of activities | [
"Find",
"latest",
"activities"
] | 92c071ad18a76d4130661da3ce47c1f0fb8ae913 | https://github.com/fotonauts/activr/blob/92c071ad18a76d4130661da3ce47c1f0fb8ae913/lib/activr/storage.rb#L102-L125 | train |
fotonauts/activr | lib/activr/storage.rb | Activr.Storage.count_activities | def count_activities(options = { })
# default options
options = {
:before => nil,
:after => nil,
:entities => { },
:only => [ ],
:except => [ ],
}.merge(options)
options[:only] = [ options[:only] ] if (options[:only] && !options[:only].is_a?(Array))
# count
self.driver.count_activities(options)
end | ruby | def count_activities(options = { })
# default options
options = {
:before => nil,
:after => nil,
:entities => { },
:only => [ ],
:except => [ ],
}.merge(options)
options[:only] = [ options[:only] ] if (options[:only] && !options[:only].is_a?(Array))
# count
self.driver.count_activities(options)
end | [
"def",
"count_activities",
"(",
"options",
"=",
"{",
"}",
")",
"# default options",
"options",
"=",
"{",
":before",
"=>",
"nil",
",",
":after",
"=>",
"nil",
",",
":entities",
"=>",
"{",
"}",
",",
":only",
"=>",
"[",
"]",
",",
":except",
"=>",
"[",
"]",
",",
"}",
".",
"merge",
"(",
"options",
")",
"options",
"[",
":only",
"]",
"=",
"[",
"options",
"[",
":only",
"]",
"]",
"if",
"(",
"options",
"[",
":only",
"]",
"&&",
"!",
"options",
"[",
":only",
"]",
".",
"is_a?",
"(",
"Array",
")",
")",
"# count",
"self",
".",
"driver",
".",
"count_activities",
"(",
"options",
")",
"end"
] | Count number of activities
@note If you use one of options selectors then you have to setup corresponding indexes in database.
@param options [Hash] Options hash
@option options [Time] :before Find activities generated before that datetime (excluding)
@option options [Time] :after Find activities generated after that datetime (excluding)
@option options [Hash{Sym=>String}] :entities Filter by entities values (empty means 'all values')
@option options [Array<Class>] :only Find only these activities
@option options [Array<Class>] :except Skip these activities
@return [Integer] Number of activities | [
"Count",
"number",
"of",
"activities"
] | 92c071ad18a76d4130661da3ce47c1f0fb8ae913 | https://github.com/fotonauts/activr/blob/92c071ad18a76d4130661da3ce47c1f0fb8ae913/lib/activr/storage.rb#L138-L152 | train |
fotonauts/activr | lib/activr/storage.rb | Activr.Storage.count_duplicate_activities | def count_duplicate_activities(activity, after)
entities = { }
activity.entities.each do |entity_name, entity|
entities[entity_name.to_sym] = entity.model_id
end
self.count_activities({
:only => activity.class,
:entities => entities,
:after => after,
})
end | ruby | def count_duplicate_activities(activity, after)
entities = { }
activity.entities.each do |entity_name, entity|
entities[entity_name.to_sym] = entity.model_id
end
self.count_activities({
:only => activity.class,
:entities => entities,
:after => after,
})
end | [
"def",
"count_duplicate_activities",
"(",
"activity",
",",
"after",
")",
"entities",
"=",
"{",
"}",
"activity",
".",
"entities",
".",
"each",
"do",
"|",
"entity_name",
",",
"entity",
"|",
"entities",
"[",
"entity_name",
".",
"to_sym",
"]",
"=",
"entity",
".",
"model_id",
"end",
"self",
".",
"count_activities",
"(",
"{",
":only",
"=>",
"activity",
".",
"class",
",",
":entities",
"=>",
"entities",
",",
":after",
"=>",
"after",
",",
"}",
")",
"end"
] | Find number of duplicate activities
@param activity [Activity] Activity to search
@param after [Time] Search after that datetime
@return [Integer] Number of activity duplicates | [
"Find",
"number",
"of",
"duplicate",
"activities"
] | 92c071ad18a76d4130661da3ce47c1f0fb8ae913 | https://github.com/fotonauts/activr/blob/92c071ad18a76d4130661da3ce47c1f0fb8ae913/lib/activr/storage.rb#L159-L171 | train |
fotonauts/activr | lib/activr/storage.rb | Activr.Storage.delete_activities_for_entity_model | def delete_activities_for_entity_model(model)
Activr.registry.activity_entities_for_model(model.class).each do |entity_name|
self.driver.delete_activities(:entities => { entity_name => model.id })
end
end | ruby | def delete_activities_for_entity_model(model)
Activr.registry.activity_entities_for_model(model.class).each do |entity_name|
self.driver.delete_activities(:entities => { entity_name => model.id })
end
end | [
"def",
"delete_activities_for_entity_model",
"(",
"model",
")",
"Activr",
".",
"registry",
".",
"activity_entities_for_model",
"(",
"model",
".",
"class",
")",
".",
"each",
"do",
"|",
"entity_name",
"|",
"self",
".",
"driver",
".",
"delete_activities",
"(",
":entities",
"=>",
"{",
"entity_name",
"=>",
"model",
".",
"id",
"}",
")",
"end",
"end"
] | Delete activities referring to given entity model instance
@param model [Object] Model instance | [
"Delete",
"activities",
"referring",
"to",
"given",
"entity",
"model",
"instance"
] | 92c071ad18a76d4130661da3ce47c1f0fb8ae913 | https://github.com/fotonauts/activr/blob/92c071ad18a76d4130661da3ce47c1f0fb8ae913/lib/activr/storage.rb#L176-L180 | train |
fotonauts/activr | lib/activr/storage.rb | Activr.Storage.find_timeline_entry | def find_timeline_entry(timeline, tl_entry_id)
timeline_entry_hash = self.driver.find_timeline_entry(timeline.kind, tl_entry_id)
if timeline_entry_hash
# run hook
self.run_hook(:did_find_timeline_entry, timeline_entry_hash, timeline.class)
# unserialize
Activr::Timeline::Entry.from_hash(timeline_entry_hash, timeline)
else
nil
end
end | ruby | def find_timeline_entry(timeline, tl_entry_id)
timeline_entry_hash = self.driver.find_timeline_entry(timeline.kind, tl_entry_id)
if timeline_entry_hash
# run hook
self.run_hook(:did_find_timeline_entry, timeline_entry_hash, timeline.class)
# unserialize
Activr::Timeline::Entry.from_hash(timeline_entry_hash, timeline)
else
nil
end
end | [
"def",
"find_timeline_entry",
"(",
"timeline",
",",
"tl_entry_id",
")",
"timeline_entry_hash",
"=",
"self",
".",
"driver",
".",
"find_timeline_entry",
"(",
"timeline",
".",
"kind",
",",
"tl_entry_id",
")",
"if",
"timeline_entry_hash",
"# run hook",
"self",
".",
"run_hook",
"(",
":did_find_timeline_entry",
",",
"timeline_entry_hash",
",",
"timeline",
".",
"class",
")",
"# unserialize",
"Activr",
"::",
"Timeline",
"::",
"Entry",
".",
"from_hash",
"(",
"timeline_entry_hash",
",",
"timeline",
")",
"else",
"nil",
"end",
"end"
] | Find a timeline entry
@param timeline [Timeline] Timeline instance
@param tl_entry_id [Object] Timeline entry id
@return [Timeline::Entry, Nil] Found timeline entry | [
"Find",
"a",
"timeline",
"entry"
] | 92c071ad18a76d4130661da3ce47c1f0fb8ae913 | https://github.com/fotonauts/activr/blob/92c071ad18a76d4130661da3ce47c1f0fb8ae913/lib/activr/storage.rb#L207-L218 | train |
fotonauts/activr | lib/activr/storage.rb | Activr.Storage.find_timeline | def find_timeline(timeline, limit, options = { })
options = {
:skip => 0,
:only => [ ],
}.merge(options)
options[:only] = [ options[:only] ] if (options[:only] && !options[:only].is_a?(Array))
result = self.driver.find_timeline_entries(timeline.kind, timeline.recipient_id, limit, options).map do |timeline_entry_hash|
# run hook
self.run_hook(:did_find_timeline_entry, timeline_entry_hash, timeline.class)
# unserialize
Activr::Timeline::Entry.from_hash(timeline_entry_hash, timeline)
end
result
end | ruby | def find_timeline(timeline, limit, options = { })
options = {
:skip => 0,
:only => [ ],
}.merge(options)
options[:only] = [ options[:only] ] if (options[:only] && !options[:only].is_a?(Array))
result = self.driver.find_timeline_entries(timeline.kind, timeline.recipient_id, limit, options).map do |timeline_entry_hash|
# run hook
self.run_hook(:did_find_timeline_entry, timeline_entry_hash, timeline.class)
# unserialize
Activr::Timeline::Entry.from_hash(timeline_entry_hash, timeline)
end
result
end | [
"def",
"find_timeline",
"(",
"timeline",
",",
"limit",
",",
"options",
"=",
"{",
"}",
")",
"options",
"=",
"{",
":skip",
"=>",
"0",
",",
":only",
"=>",
"[",
"]",
",",
"}",
".",
"merge",
"(",
"options",
")",
"options",
"[",
":only",
"]",
"=",
"[",
"options",
"[",
":only",
"]",
"]",
"if",
"(",
"options",
"[",
":only",
"]",
"&&",
"!",
"options",
"[",
":only",
"]",
".",
"is_a?",
"(",
"Array",
")",
")",
"result",
"=",
"self",
".",
"driver",
".",
"find_timeline_entries",
"(",
"timeline",
".",
"kind",
",",
"timeline",
".",
"recipient_id",
",",
"limit",
",",
"options",
")",
".",
"map",
"do",
"|",
"timeline_entry_hash",
"|",
"# run hook",
"self",
".",
"run_hook",
"(",
":did_find_timeline_entry",
",",
"timeline_entry_hash",
",",
"timeline",
".",
"class",
")",
"# unserialize",
"Activr",
"::",
"Timeline",
"::",
"Entry",
".",
"from_hash",
"(",
"timeline_entry_hash",
",",
"timeline",
")",
"end",
"result",
"end"
] | Find timeline entries by descending timestamp
@param timeline [Timeline] Timeline instance
@param limit [Integer] Max number of entries to find
@param options [Hash] Options hash
@option options [Integer] :skip Number of entries to skip (default: 0)
@option options [Array<Timeline::Route>] :only An array of routes to fetch
@return [Array<Timeline::Entry>] An array of timeline entries | [
"Find",
"timeline",
"entries",
"by",
"descending",
"timestamp"
] | 92c071ad18a76d4130661da3ce47c1f0fb8ae913 | https://github.com/fotonauts/activr/blob/92c071ad18a76d4130661da3ce47c1f0fb8ae913/lib/activr/storage.rb#L228-L245 | train |
fotonauts/activr | lib/activr/storage.rb | Activr.Storage.count_timeline | def count_timeline(timeline, options = { })
options = {
:only => [ ],
}.merge(options)
options[:only] = [ options[:only] ] if (options[:only] && !options[:only].is_a?(Array))
self.driver.count_timeline_entries(timeline.kind, timeline.recipient_id, options)
end | ruby | def count_timeline(timeline, options = { })
options = {
:only => [ ],
}.merge(options)
options[:only] = [ options[:only] ] if (options[:only] && !options[:only].is_a?(Array))
self.driver.count_timeline_entries(timeline.kind, timeline.recipient_id, options)
end | [
"def",
"count_timeline",
"(",
"timeline",
",",
"options",
"=",
"{",
"}",
")",
"options",
"=",
"{",
":only",
"=>",
"[",
"]",
",",
"}",
".",
"merge",
"(",
"options",
")",
"options",
"[",
":only",
"]",
"=",
"[",
"options",
"[",
":only",
"]",
"]",
"if",
"(",
"options",
"[",
":only",
"]",
"&&",
"!",
"options",
"[",
":only",
"]",
".",
"is_a?",
"(",
"Array",
")",
")",
"self",
".",
"driver",
".",
"count_timeline_entries",
"(",
"timeline",
".",
"kind",
",",
"timeline",
".",
"recipient_id",
",",
"options",
")",
"end"
] | Count number of timeline entries
@param timeline [Timeline] Timeline instance
@param options [Hash] Options hash
@option options [Array<Timeline::Route>] :only An array of routes to count
@return [Integer] Number of timeline entries in given timeline | [
"Count",
"number",
"of",
"timeline",
"entries"
] | 92c071ad18a76d4130661da3ce47c1f0fb8ae913 | https://github.com/fotonauts/activr/blob/92c071ad18a76d4130661da3ce47c1f0fb8ae913/lib/activr/storage.rb#L253-L261 | train |
fotonauts/activr | lib/activr/storage.rb | Activr.Storage.delete_timeline | def delete_timeline(timeline, options = { })
# default options
options = {
:before => nil,
:entities => { },
}.merge(options)
self.driver.delete_timeline_entries(timeline.kind, timeline.recipient_id, options)
end | ruby | def delete_timeline(timeline, options = { })
# default options
options = {
:before => nil,
:entities => { },
}.merge(options)
self.driver.delete_timeline_entries(timeline.kind, timeline.recipient_id, options)
end | [
"def",
"delete_timeline",
"(",
"timeline",
",",
"options",
"=",
"{",
"}",
")",
"# default options",
"options",
"=",
"{",
":before",
"=>",
"nil",
",",
":entities",
"=>",
"{",
"}",
",",
"}",
".",
"merge",
"(",
"options",
")",
"self",
".",
"driver",
".",
"delete_timeline_entries",
"(",
"timeline",
".",
"kind",
",",
"timeline",
".",
"recipient_id",
",",
"options",
")",
"end"
] | Delete timeline entries
@param timeline [Timeline] Timeline instance
@param options [Hash] Options hash
@option options [Time] :before Delete only timeline entries which timestamp is before that datetime (excluding)
@option options [Hash{Sym=>String}] :entity Delete only timeline entries with these entities values | [
"Delete",
"timeline",
"entries"
] | 92c071ad18a76d4130661da3ce47c1f0fb8ae913 | https://github.com/fotonauts/activr/blob/92c071ad18a76d4130661da3ce47c1f0fb8ae913/lib/activr/storage.rb#L269-L277 | train |
fotonauts/activr | lib/activr/storage.rb | Activr.Storage.delete_timeline_entries_for_entity_model | def delete_timeline_entries_for_entity_model(model)
Activr.registry.timeline_entities_for_model(model.class).each do |timeline_class, entities|
entities.each do |entity_name|
self.driver.delete_timeline_entries(timeline_class.kind, nil, :entities => { entity_name => model.id })
end
end
end | ruby | def delete_timeline_entries_for_entity_model(model)
Activr.registry.timeline_entities_for_model(model.class).each do |timeline_class, entities|
entities.each do |entity_name|
self.driver.delete_timeline_entries(timeline_class.kind, nil, :entities => { entity_name => model.id })
end
end
end | [
"def",
"delete_timeline_entries_for_entity_model",
"(",
"model",
")",
"Activr",
".",
"registry",
".",
"timeline_entities_for_model",
"(",
"model",
".",
"class",
")",
".",
"each",
"do",
"|",
"timeline_class",
",",
"entities",
"|",
"entities",
".",
"each",
"do",
"|",
"entity_name",
"|",
"self",
".",
"driver",
".",
"delete_timeline_entries",
"(",
"timeline_class",
".",
"kind",
",",
"nil",
",",
":entities",
"=>",
"{",
"entity_name",
"=>",
"model",
".",
"id",
"}",
")",
"end",
"end",
"end"
] | Delete timeline entries referring to given entity model instance
@param model [Object] Model instance | [
"Delete",
"timeline",
"entries",
"referring",
"to",
"given",
"entity",
"model",
"instance"
] | 92c071ad18a76d4130661da3ce47c1f0fb8ae913 | https://github.com/fotonauts/activr/blob/92c071ad18a76d4130661da3ce47c1f0fb8ae913/lib/activr/storage.rb#L282-L288 | train |
fotonauts/activr | lib/activr/storage.rb | Activr.Storage.run_hook | def run_hook(name, *args)
return if @hooks[name].blank?
@hooks[name].each do |hook|
args.any? ? hook.call(*args) : hook.call
end
end | ruby | def run_hook(name, *args)
return if @hooks[name].blank?
@hooks[name].each do |hook|
args.any? ? hook.call(*args) : hook.call
end
end | [
"def",
"run_hook",
"(",
"name",
",",
"*",
"args",
")",
"return",
"if",
"@hooks",
"[",
"name",
"]",
".",
"blank?",
"@hooks",
"[",
"name",
"]",
".",
"each",
"do",
"|",
"hook",
"|",
"args",
".",
"any?",
"?",
"hook",
".",
"call",
"(",
"args",
")",
":",
"hook",
".",
"call",
"end",
"end"
] | Run a hook
@api private
@param name [Symbol] Hook name
@param args [Array] Hook arguments | [
"Run",
"a",
"hook"
] | 92c071ad18a76d4130661da3ce47c1f0fb8ae913 | https://github.com/fotonauts/activr/blob/92c071ad18a76d4130661da3ce47c1f0fb8ae913/lib/activr/storage.rb#L387-L393 | train |
polypressure/formant | lib/formant.rb | Formant.FormObject.reformatted! | def reformatted!
self.class.format_fields.each do |field_name, format_method, options|
formatted_value = send(format_method, get_field(field_name), options)
set_field(field_name, formatted_value)
end
self
end | ruby | def reformatted!
self.class.format_fields.each do |field_name, format_method, options|
formatted_value = send(format_method, get_field(field_name), options)
set_field(field_name, formatted_value)
end
self
end | [
"def",
"reformatted!",
"self",
".",
"class",
".",
"format_fields",
".",
"each",
"do",
"|",
"field_name",
",",
"format_method",
",",
"options",
"|",
"formatted_value",
"=",
"send",
"(",
"format_method",
",",
"get_field",
"(",
"field_name",
")",
",",
"options",
")",
"set_field",
"(",
"field_name",
",",
"formatted_value",
")",
"end",
"self",
"end"
] | Triger any formatting rules specified with the reformat directive.
The attributes are reformatted and mutated in place.
Returns an instance of the form object. | [
"Triger",
"any",
"formatting",
"rules",
"specified",
"with",
"the",
"reformat",
"directive",
".",
"The",
"attributes",
"are",
"reformatted",
"and",
"mutated",
"in",
"place",
"."
] | fbfe7095542f92ef3d1e659038c4257aafe417c5 | https://github.com/polypressure/formant/blob/fbfe7095542f92ef3d1e659038c4257aafe417c5/lib/formant.rb#L101-L107 | train |
polypressure/formant | lib/formant.rb | Formant.FormObject.to_params | def to_params
attrs = Hash.new
instance_variables.each do |ivar|
name = ivar[1..-1]
attrs[name.to_sym] = instance_variable_get(ivar) if respond_to? "#{name}="
end
attrs
end | ruby | def to_params
attrs = Hash.new
instance_variables.each do |ivar|
name = ivar[1..-1]
attrs[name.to_sym] = instance_variable_get(ivar) if respond_to? "#{name}="
end
attrs
end | [
"def",
"to_params",
"attrs",
"=",
"Hash",
".",
"new",
"instance_variables",
".",
"each",
"do",
"|",
"ivar",
"|",
"name",
"=",
"ivar",
"[",
"1",
"..",
"-",
"1",
"]",
"attrs",
"[",
"name",
".",
"to_sym",
"]",
"=",
"instance_variable_get",
"(",
"ivar",
")",
"if",
"respond_to?",
"\"#{name}=\"",
"end",
"attrs",
"end"
] | Return all the attributes as a params hash. | [
"Return",
"all",
"the",
"attributes",
"as",
"a",
"params",
"hash",
"."
] | fbfe7095542f92ef3d1e659038c4257aafe417c5 | https://github.com/polypressure/formant/blob/fbfe7095542f92ef3d1e659038c4257aafe417c5/lib/formant.rb#L112-L119 | train |
cjbottaro/param_protected | lib/param_protected/protector.rb | ParamProtected.Protector.merge_protections | def merge_protections(protections, protected_params)
protected_params.each do |k,v|
if protections[k].is_a?(Hash)
merge_protections(protections[k], v) if v
else
protections[k] = v
end
end
protections
end | ruby | def merge_protections(protections, protected_params)
protected_params.each do |k,v|
if protections[k].is_a?(Hash)
merge_protections(protections[k], v) if v
else
protections[k] = v
end
end
protections
end | [
"def",
"merge_protections",
"(",
"protections",
",",
"protected_params",
")",
"protected_params",
".",
"each",
"do",
"|",
"k",
",",
"v",
"|",
"if",
"protections",
"[",
"k",
"]",
".",
"is_a?",
"(",
"Hash",
")",
"merge_protections",
"(",
"protections",
"[",
"k",
"]",
",",
"v",
")",
"if",
"v",
"else",
"protections",
"[",
"k",
"]",
"=",
"v",
"end",
"end",
"protections",
"end"
] | Merge protections for the same params into one so as to allow extension of them
in inheriting controllers.
Mutating the first argument is okay since this method is used within inject only.
Example:
merge_protections({ :foo => { :qux => nil }, :bar => { :baz => nil, :qux => nil } },
{ :foo => { :baz => nil, :qux => { :foo => nil } } })
=>
{ :foo => { :baz => nil, :qux => { :foo => nil } }, :bar => { :baz =>nil, :qux => nil } } | [
"Merge",
"protections",
"for",
"the",
"same",
"params",
"into",
"one",
"so",
"as",
"to",
"allow",
"extension",
"of",
"them",
"in",
"inheriting",
"controllers",
"."
] | 24e2d297b0def7498af02758455d89bd87b62dbc | https://github.com/cjbottaro/param_protected/blob/24e2d297b0def7498af02758455d89bd87b62dbc/lib/param_protected/protector.rb#L47-L57 | train |
alexanderbez/sounddrop | lib/sounddrop/drop.rb | SoundDrop.Drop.media_url | def media_url
begin
r = HTTParty.get("https://api.soundcloud.com/i1/tracks/#{id}/streams?client_id=#{@CLIENT.client_id}")
r['http_mp3_128_url']
rescue Exception => ex
raise SoundDrop::Exception::FailedRequest.new(ex)
end
end | ruby | def media_url
begin
r = HTTParty.get("https://api.soundcloud.com/i1/tracks/#{id}/streams?client_id=#{@CLIENT.client_id}")
r['http_mp3_128_url']
rescue Exception => ex
raise SoundDrop::Exception::FailedRequest.new(ex)
end
end | [
"def",
"media_url",
"begin",
"r",
"=",
"HTTParty",
".",
"get",
"(",
"\"https://api.soundcloud.com/i1/tracks/#{id}/streams?client_id=#{@CLIENT.client_id}\"",
")",
"r",
"[",
"'http_mp3_128_url'",
"]",
"rescue",
"Exception",
"=>",
"ex",
"raise",
"SoundDrop",
"::",
"Exception",
"::",
"FailedRequest",
".",
"new",
"(",
"ex",
")",
"end",
"end"
] | Track media url | [
"Track",
"media",
"url"
] | 563903234cb8a86d2fd8c19f2991437a5dc71d7e | https://github.com/alexanderbez/sounddrop/blob/563903234cb8a86d2fd8c19f2991437a5dc71d7e/lib/sounddrop/drop.rb#L35-L42 | train |
kvokka/active_admin_simple_life | lib/active_admin_simple_life/simple_menu.rb | ActiveAdminSimpleLife.SimpleMenu.for | def for(klass, options = {}, &blk)
ActiveAdmin.register klass do
options = {index: {}, form: {}, filter: {}}.merge options
permitted_params = options.delete :permitted_params
permit_params(*(klass.main_fields + (permitted_params || [])))
# menu_options = options.slice(:priority, :parent, :if)
menu options if options.any?
actions :all, except: [:show]
controller.class_variable_set(:@@permitted_params, permitted_params)
controller.class_variable_set(:@@klass, klass)
controller do
def scoped_collection
permitted_params = self.class.class_variable_get :@@permitted_params
self.class.class_variable_get(:@@klass).includes(*permitted_params.map{|symbol| ExtensionedSymbol.new(symbol).cut_id})
end
end if permitted_params
%i[index filter form].each do |action|
send "#{action}_for_main_fields", klass, options[action] unless options[action][:skip] == true
end
instance_exec &blk if block_given?
end
end | ruby | def for(klass, options = {}, &blk)
ActiveAdmin.register klass do
options = {index: {}, form: {}, filter: {}}.merge options
permitted_params = options.delete :permitted_params
permit_params(*(klass.main_fields + (permitted_params || [])))
# menu_options = options.slice(:priority, :parent, :if)
menu options if options.any?
actions :all, except: [:show]
controller.class_variable_set(:@@permitted_params, permitted_params)
controller.class_variable_set(:@@klass, klass)
controller do
def scoped_collection
permitted_params = self.class.class_variable_get :@@permitted_params
self.class.class_variable_get(:@@klass).includes(*permitted_params.map{|symbol| ExtensionedSymbol.new(symbol).cut_id})
end
end if permitted_params
%i[index filter form].each do |action|
send "#{action}_for_main_fields", klass, options[action] unless options[action][:skip] == true
end
instance_exec &blk if block_given?
end
end | [
"def",
"for",
"(",
"klass",
",",
"options",
"=",
"{",
"}",
",",
"&",
"blk",
")",
"ActiveAdmin",
".",
"register",
"klass",
"do",
"options",
"=",
"{",
"index",
":",
"{",
"}",
",",
"form",
":",
"{",
"}",
",",
"filter",
":",
"{",
"}",
"}",
".",
"merge",
"options",
"permitted_params",
"=",
"options",
".",
"delete",
":permitted_params",
"permit_params",
"(",
"(",
"klass",
".",
"main_fields",
"+",
"(",
"permitted_params",
"||",
"[",
"]",
")",
")",
")",
"# menu_options = options.slice(:priority, :parent, :if)",
"menu",
"options",
"if",
"options",
".",
"any?",
"actions",
":all",
",",
"except",
":",
"[",
":show",
"]",
"controller",
".",
"class_variable_set",
"(",
":@@permitted_params",
",",
"permitted_params",
")",
"controller",
".",
"class_variable_set",
"(",
":@@klass",
",",
"klass",
")",
"controller",
"do",
"def",
"scoped_collection",
"permitted_params",
"=",
"self",
".",
"class",
".",
"class_variable_get",
":@@permitted_params",
"self",
".",
"class",
".",
"class_variable_get",
"(",
":@@klass",
")",
".",
"includes",
"(",
"permitted_params",
".",
"map",
"{",
"|",
"symbol",
"|",
"ExtensionedSymbol",
".",
"new",
"(",
"symbol",
")",
".",
"cut_id",
"}",
")",
"end",
"end",
"if",
"permitted_params",
"%i[",
"index",
"filter",
"form",
"]",
".",
"each",
"do",
"|",
"action",
"|",
"send",
"\"#{action}_for_main_fields\"",
",",
"klass",
",",
"options",
"[",
"action",
"]",
"unless",
"options",
"[",
"action",
"]",
"[",
":skip",
"]",
"==",
"true",
"end",
"instance_exec",
"blk",
"if",
"block_given?",
"end",
"end"
] | for proper work, model must have class method `mail_fields`, which return array of field symbols.
references write as is, like `foo_id`
in options can take:
menu_priority:integer
menu_parent:string
permitted_params:array for some additions to main_fields permitted params
def simple_menu_for(klass, options = {}) | [
"for",
"proper",
"work",
"model",
"must",
"have",
"class",
"method",
"mail_fields",
"which",
"return",
"array",
"of",
"field",
"symbols",
".",
"references",
"write",
"as",
"is",
"like",
"foo_id"
] | 050ac1a87462c2b57bd42bae43df3cb0c238c42b | https://github.com/kvokka/active_admin_simple_life/blob/050ac1a87462c2b57bd42bae43df3cb0c238c42b/lib/active_admin_simple_life/simple_menu.rb#L14-L39 | train |
ChrisSandison/missing_text | lib/missing_text/diff.rb | MissingText.Diff.generate_diff_for_language | def generate_diff_for_language(current_language, target_language)
current_langmap = langmap[current_language]
target_langmap = langmap[target_language]
diffmap_key = [current_language, target_language]
diffmap[diffmap_key] = current_langmap - target_langmap
end | ruby | def generate_diff_for_language(current_language, target_language)
current_langmap = langmap[current_language]
target_langmap = langmap[target_language]
diffmap_key = [current_language, target_language]
diffmap[diffmap_key] = current_langmap - target_langmap
end | [
"def",
"generate_diff_for_language",
"(",
"current_language",
",",
"target_language",
")",
"current_langmap",
"=",
"langmap",
"[",
"current_language",
"]",
"target_langmap",
"=",
"langmap",
"[",
"target_language",
"]",
"diffmap_key",
"=",
"[",
"current_language",
",",
"target_language",
"]",
"diffmap",
"[",
"diffmap_key",
"]",
"=",
"current_langmap",
"-",
"target_langmap",
"end"
] | a diffmap shows what is missing between two languages
the key is a two-element array, the first element is the current language
and the second element is the target language
for example
diffmap: {[:en, :fr] => [[:obj3], ...]}
means that fr was examined against en, where en had an entry for obj3 that fr didn't | [
"a",
"diffmap",
"shows",
"what",
"is",
"missing",
"between",
"two",
"languages",
"the",
"key",
"is",
"a",
"two",
"-",
"element",
"array",
"the",
"first",
"element",
"is",
"the",
"current",
"language",
"and",
"the",
"second",
"element",
"is",
"the",
"target",
"language"
] | dd33f0118f0a69798537e0280a6c62dc387f3e81 | https://github.com/ChrisSandison/missing_text/blob/dd33f0118f0a69798537e0280a6c62dc387f3e81/lib/missing_text/diff.rb#L106-L111 | train |
ChrisSandison/missing_text | lib/missing_text/diff.rb | MissingText.Diff.make_keymap | def make_keymap(langmap_entry, language)
language.each do |key, value|
if value.is_a? Hash
make_keymap_for(langmap_entry, value, [key.to_sym])
else
langmap_entry << [key.to_sym]
end
end
end | ruby | def make_keymap(langmap_entry, language)
language.each do |key, value|
if value.is_a? Hash
make_keymap_for(langmap_entry, value, [key.to_sym])
else
langmap_entry << [key.to_sym]
end
end
end | [
"def",
"make_keymap",
"(",
"langmap_entry",
",",
"language",
")",
"language",
".",
"each",
"do",
"|",
"key",
",",
"value",
"|",
"if",
"value",
".",
"is_a?",
"Hash",
"make_keymap_for",
"(",
"langmap_entry",
",",
"value",
",",
"[",
"key",
".",
"to_sym",
"]",
")",
"else",
"langmap_entry",
"<<",
"[",
"key",
".",
"to_sym",
"]",
"end",
"end",
"end"
] | outer method for creating keymap on parent hash | [
"outer",
"method",
"for",
"creating",
"keymap",
"on",
"parent",
"hash"
] | dd33f0118f0a69798537e0280a6c62dc387f3e81 | https://github.com/ChrisSandison/missing_text/blob/dd33f0118f0a69798537e0280a6c62dc387f3e81/lib/missing_text/diff.rb#L133-L141 | train |
ChrisSandison/missing_text | lib/missing_text/diff.rb | MissingText.Diff.make_keymap_for | def make_keymap_for(langmap_entry, language, key_path)
language.each do |key, value|
# need a new value of this for every value we are looking at because we want all route traces to have single threading for when they are called again
new_path = Array.new key_path
if value.is_a? Hash
make_keymap_for(langmap_entry, value, new_path.push(key.to_s.to_sym))
else
langmap_entry << new_path.push(key.to_s.to_sym)
end
end
end | ruby | def make_keymap_for(langmap_entry, language, key_path)
language.each do |key, value|
# need a new value of this for every value we are looking at because we want all route traces to have single threading for when they are called again
new_path = Array.new key_path
if value.is_a? Hash
make_keymap_for(langmap_entry, value, new_path.push(key.to_s.to_sym))
else
langmap_entry << new_path.push(key.to_s.to_sym)
end
end
end | [
"def",
"make_keymap_for",
"(",
"langmap_entry",
",",
"language",
",",
"key_path",
")",
"language",
".",
"each",
"do",
"|",
"key",
",",
"value",
"|",
"# need a new value of this for every value we are looking at because we want all route traces to have single threading for when they are called again",
"new_path",
"=",
"Array",
".",
"new",
"key_path",
"if",
"value",
".",
"is_a?",
"Hash",
"make_keymap_for",
"(",
"langmap_entry",
",",
"value",
",",
"new_path",
".",
"push",
"(",
"key",
".",
"to_s",
".",
"to_sym",
")",
")",
"else",
"langmap_entry",
"<<",
"new_path",
".",
"push",
"(",
"key",
".",
"to_s",
".",
"to_sym",
")",
"end",
"end",
"end"
] | recursive helper for creating keymap on children hashes | [
"recursive",
"helper",
"for",
"creating",
"keymap",
"on",
"children",
"hashes"
] | dd33f0118f0a69798537e0280a6c62dc387f3e81 | https://github.com/ChrisSandison/missing_text/blob/dd33f0118f0a69798537e0280a6c62dc387f3e81/lib/missing_text/diff.rb#L144-L154 | train |
teodor-pripoae/scalaroid | lib/scalaroid/transaction_single_op.rb | Scalaroid.TransactionSingleOp.write | def write(key, value, binary = false)
value = @conn.class.encode_value(value, binary)
result = @conn.call(:write, [key, value])
@conn.class.check_fail_abort(result)
@conn.class.process_result_commit(result)
end | ruby | def write(key, value, binary = false)
value = @conn.class.encode_value(value, binary)
result = @conn.call(:write, [key, value])
@conn.class.check_fail_abort(result)
@conn.class.process_result_commit(result)
end | [
"def",
"write",
"(",
"key",
",",
"value",
",",
"binary",
"=",
"false",
")",
"value",
"=",
"@conn",
".",
"class",
".",
"encode_value",
"(",
"value",
",",
"binary",
")",
"result",
"=",
"@conn",
".",
"call",
"(",
":write",
",",
"[",
"key",
",",
"value",
"]",
")",
"@conn",
".",
"class",
".",
"check_fail_abort",
"(",
"result",
")",
"@conn",
".",
"class",
".",
"process_result_commit",
"(",
"result",
")",
"end"
] | Write the value to key. | [
"Write",
"the",
"value",
"to",
"key",
"."
] | 4e9e90e71ce3008da79a72eae40fe2f187580be2 | https://github.com/teodor-pripoae/scalaroid/blob/4e9e90e71ce3008da79a72eae40fe2f187580be2/lib/scalaroid/transaction_single_op.rb#L85-L90 | train |
teodor-pripoae/scalaroid | lib/scalaroid/transaction_single_op.rb | Scalaroid.TransactionSingleOp.add_del_on_list | def add_del_on_list(key, to_add, to_remove)
result = @conn.call(:add_del_on_list, [key, to_add, to_remove])
@conn.class.check_fail_abort(result)
@conn.class.process_result_add_del_on_list(result)
end | ruby | def add_del_on_list(key, to_add, to_remove)
result = @conn.call(:add_del_on_list, [key, to_add, to_remove])
@conn.class.check_fail_abort(result)
@conn.class.process_result_add_del_on_list(result)
end | [
"def",
"add_del_on_list",
"(",
"key",
",",
"to_add",
",",
"to_remove",
")",
"result",
"=",
"@conn",
".",
"call",
"(",
":add_del_on_list",
",",
"[",
"key",
",",
"to_add",
",",
"to_remove",
"]",
")",
"@conn",
".",
"class",
".",
"check_fail_abort",
"(",
"result",
")",
"@conn",
".",
"class",
".",
"process_result_add_del_on_list",
"(",
"result",
")",
"end"
] | Changes the list stored at the given key, i.e. first adds all items in
to_add then removes all items in to_remove.
Both, to_add and to_remove, must be lists.
Assumes en empty list if no value exists at key. | [
"Changes",
"the",
"list",
"stored",
"at",
"the",
"given",
"key",
"i",
".",
"e",
".",
"first",
"adds",
"all",
"items",
"in",
"to_add",
"then",
"removes",
"all",
"items",
"in",
"to_remove",
".",
"Both",
"to_add",
"and",
"to_remove",
"must",
"be",
"lists",
".",
"Assumes",
"en",
"empty",
"list",
"if",
"no",
"value",
"exists",
"at",
"key",
"."
] | 4e9e90e71ce3008da79a72eae40fe2f187580be2 | https://github.com/teodor-pripoae/scalaroid/blob/4e9e90e71ce3008da79a72eae40fe2f187580be2/lib/scalaroid/transaction_single_op.rb#L96-L100 | train |
teodor-pripoae/scalaroid | lib/scalaroid/transaction_single_op.rb | Scalaroid.TransactionSingleOp.add_on_nr | def add_on_nr(key, to_add)
result = @conn.call(:add_on_nr, [key, to_add])
@conn.class.check_fail_abort(result)
@conn.class.process_result_add_on_nr(result)
end | ruby | def add_on_nr(key, to_add)
result = @conn.call(:add_on_nr, [key, to_add])
@conn.class.check_fail_abort(result)
@conn.class.process_result_add_on_nr(result)
end | [
"def",
"add_on_nr",
"(",
"key",
",",
"to_add",
")",
"result",
"=",
"@conn",
".",
"call",
"(",
":add_on_nr",
",",
"[",
"key",
",",
"to_add",
"]",
")",
"@conn",
".",
"class",
".",
"check_fail_abort",
"(",
"result",
")",
"@conn",
".",
"class",
".",
"process_result_add_on_nr",
"(",
"result",
")",
"end"
] | Changes the number stored at the given key, i.e. adds some value.
Assumes 0 if no value exists at key. | [
"Changes",
"the",
"number",
"stored",
"at",
"the",
"given",
"key",
"i",
".",
"e",
".",
"adds",
"some",
"value",
".",
"Assumes",
"0",
"if",
"no",
"value",
"exists",
"at",
"key",
"."
] | 4e9e90e71ce3008da79a72eae40fe2f187580be2 | https://github.com/teodor-pripoae/scalaroid/blob/4e9e90e71ce3008da79a72eae40fe2f187580be2/lib/scalaroid/transaction_single_op.rb#L104-L108 | train |
NUBIC/psc.rb | lib/psc/connection.rb | Psc.Connection.has_superclass? | def has_superclass?(child, ancestor)
if child.superclass == ancestor
true
elsif child.superclass.nil?
false
else
has_superclass?(child.superclass, ancestor)
end
end | ruby | def has_superclass?(child, ancestor)
if child.superclass == ancestor
true
elsif child.superclass.nil?
false
else
has_superclass?(child.superclass, ancestor)
end
end | [
"def",
"has_superclass?",
"(",
"child",
",",
"ancestor",
")",
"if",
"child",
".",
"superclass",
"==",
"ancestor",
"true",
"elsif",
"child",
".",
"superclass",
".",
"nil?",
"false",
"else",
"has_superclass?",
"(",
"child",
".",
"superclass",
",",
"ancestor",
")",
"end",
"end"
] | It seems like there must be a builtin for this, but I'm not
finding it. | [
"It",
"seems",
"like",
"there",
"must",
"be",
"a",
"builtin",
"for",
"this",
"but",
"I",
"m",
"not",
"finding",
"it",
"."
] | 4ac9df03fe655094e4889966a9a1e029583a38de | https://github.com/NUBIC/psc.rb/blob/4ac9df03fe655094e4889966a9a1e029583a38de/lib/psc/connection.rb#L87-L95 | train |
jonahoffline/endi_feed | lib/endi_feed/news.rb | EndiFeed.News.process_news | def process_news(total = 25)
items.map.with_index do |item, num|
@headlines << format_headline(item, num) if total_met?(total)
end.compact || nil
end | ruby | def process_news(total = 25)
items.map.with_index do |item, num|
@headlines << format_headline(item, num) if total_met?(total)
end.compact || nil
end | [
"def",
"process_news",
"(",
"total",
"=",
"25",
")",
"items",
".",
"map",
".",
"with_index",
"do",
"|",
"item",
",",
"num",
"|",
"@headlines",
"<<",
"format_headline",
"(",
"item",
",",
"num",
")",
"if",
"total_met?",
"(",
"total",
")",
"end",
".",
"compact",
"||",
"nil",
"end"
] | Handles iteration of each headline
@return [Array<String>] news headlines | [
"Handles",
"iteration",
"of",
"each",
"headline"
] | d698a7104fb74273098734d62c2291a47f861115 | https://github.com/jonahoffline/endi_feed/blob/d698a7104fb74273098734d62c2291a47f861115/lib/endi_feed/news.rb#L93-L97 | train |
cul/cul-ldap | lib/cul/ldap.rb | Cul.LDAP.find_by_uni | def find_by_uni(uni)
entries = search(base: "ou=People,o=Columbia University, c=US", filter: Net::LDAP::Filter.eq("uid", uni))
(entries.count == 1) ? entries.first : nil
end | ruby | def find_by_uni(uni)
entries = search(base: "ou=People,o=Columbia University, c=US", filter: Net::LDAP::Filter.eq("uid", uni))
(entries.count == 1) ? entries.first : nil
end | [
"def",
"find_by_uni",
"(",
"uni",
")",
"entries",
"=",
"search",
"(",
"base",
":",
"\"ou=People,o=Columbia University, c=US\"",
",",
"filter",
":",
"Net",
"::",
"LDAP",
"::",
"Filter",
".",
"eq",
"(",
"\"uid\"",
",",
"uni",
")",
")",
"(",
"entries",
".",
"count",
"==",
"1",
")",
"?",
"entries",
".",
"first",
":",
"nil",
"end"
] | LDAP lookup based on UNI. If record could not be found returns nil.
@param [String] uni
@return [Cul::LDAP::Entry] containing all the ldap information available for the uni given
@return [nil] if record for uni could not be found, or more than one record was found | [
"LDAP",
"lookup",
"based",
"on",
"UNI",
".",
"If",
"record",
"could",
"not",
"be",
"found",
"returns",
"nil",
"."
] | 07c35bbf1c2fdc73719e32c39397c3971c0878bc | https://github.com/cul/cul-ldap/blob/07c35bbf1c2fdc73719e32c39397c3971c0878bc/lib/cul/ldap.rb#L28-L31 | train |
cul/cul-ldap | lib/cul/ldap.rb | Cul.LDAP.find_by_name | def find_by_name(name)
if name.include?(',')
name = name.split(',').map(&:strip).reverse.join(" ")
end
entries = search(base: "ou=People,o=Columbia University, c=US", filter: Net::LDAP::Filter.eq("cn", name))
(entries.count == 1) ? entries.first : nil
end | ruby | def find_by_name(name)
if name.include?(',')
name = name.split(',').map(&:strip).reverse.join(" ")
end
entries = search(base: "ou=People,o=Columbia University, c=US", filter: Net::LDAP::Filter.eq("cn", name))
(entries.count == 1) ? entries.first : nil
end | [
"def",
"find_by_name",
"(",
"name",
")",
"if",
"name",
".",
"include?",
"(",
"','",
")",
"name",
"=",
"name",
".",
"split",
"(",
"','",
")",
".",
"map",
"(",
":strip",
")",
".",
"reverse",
".",
"join",
"(",
"\" \"",
")",
"end",
"entries",
"=",
"search",
"(",
"base",
":",
"\"ou=People,o=Columbia University, c=US\"",
",",
"filter",
":",
"Net",
"::",
"LDAP",
"::",
"Filter",
".",
"eq",
"(",
"\"cn\"",
",",
"name",
")",
")",
"(",
"entries",
".",
"count",
"==",
"1",
")",
"?",
"entries",
".",
"first",
":",
"nil",
"end"
] | LDAP lookup based on name.
@param [String] name
@return [Cul::LDAP::Entry] containing the entry matching this name, if it is unique
@return [nil] if record could not be found or if there is more than one match | [
"LDAP",
"lookup",
"based",
"on",
"name",
"."
] | 07c35bbf1c2fdc73719e32c39397c3971c0878bc | https://github.com/cul/cul-ldap/blob/07c35bbf1c2fdc73719e32c39397c3971c0878bc/lib/cul/ldap.rb#L38-L44 | train |
thirst/glass-rails | lib/glass/client.rb | Glass.Client.rest_action | def rest_action(options, action="insert")
body_object = json_content(options, action)
inserting_content = { api_method: mirror_api.timeline.send(action),
body_object: body_object}
end | ruby | def rest_action(options, action="insert")
body_object = json_content(options, action)
inserting_content = { api_method: mirror_api.timeline.send(action),
body_object: body_object}
end | [
"def",
"rest_action",
"(",
"options",
",",
"action",
"=",
"\"insert\"",
")",
"body_object",
"=",
"json_content",
"(",
"options",
",",
"action",
")",
"inserting_content",
"=",
"{",
"api_method",
":",
"mirror_api",
".",
"timeline",
".",
"send",
"(",
"action",
")",
",",
"body_object",
":",
"body_object",
"}",
"end"
] | optional parameter is merged into the content hash
before sending. good for specifying more application
specific stuff like speakableText parameters. | [
"optional",
"parameter",
"is",
"merged",
"into",
"the",
"content",
"hash",
"before",
"sending",
".",
"good",
"for",
"specifying",
"more",
"application",
"specific",
"stuff",
"like",
"speakableText",
"parameters",
"."
] | a581281a9c5d09ed21ba7369b5b714f1c95d629d | https://github.com/thirst/glass-rails/blob/a581281a9c5d09ed21ba7369b5b714f1c95d629d/lib/glass/client.rb#L88-L92 | train |
thirst/glass-rails | lib/glass/client.rb | Glass.Client.list | def list(opts={as_hash: true})
page_token = nil
parameters = {}
self.timeline_list = []
begin
parameters = {}
parameters['pageToken'] = page_token if page_token.present?
api_result = google_client.execute(api_method: mirror_api.timeline.list,
parameters: parameters)
if api_result.success?
timeline_items = api_result.data
page_token = nil if timeline_items.items.empty?
if timeline_items.items.any?
@timeline_list.concat(timeline_items.items)
page_token = timeline_items.next_page_token
end
else
puts "An error occurred: #{api_result.data['error']['message']}"
page_token = nil
end
end while page_token.to_s != ''
timeline_list(opts)
end | ruby | def list(opts={as_hash: true})
page_token = nil
parameters = {}
self.timeline_list = []
begin
parameters = {}
parameters['pageToken'] = page_token if page_token.present?
api_result = google_client.execute(api_method: mirror_api.timeline.list,
parameters: parameters)
if api_result.success?
timeline_items = api_result.data
page_token = nil if timeline_items.items.empty?
if timeline_items.items.any?
@timeline_list.concat(timeline_items.items)
page_token = timeline_items.next_page_token
end
else
puts "An error occurred: #{api_result.data['error']['message']}"
page_token = nil
end
end while page_token.to_s != ''
timeline_list(opts)
end | [
"def",
"list",
"(",
"opts",
"=",
"{",
"as_hash",
":",
"true",
"}",
")",
"page_token",
"=",
"nil",
"parameters",
"=",
"{",
"}",
"self",
".",
"timeline_list",
"=",
"[",
"]",
"begin",
"parameters",
"=",
"{",
"}",
"parameters",
"[",
"'pageToken'",
"]",
"=",
"page_token",
"if",
"page_token",
".",
"present?",
"api_result",
"=",
"google_client",
".",
"execute",
"(",
"api_method",
":",
"mirror_api",
".",
"timeline",
".",
"list",
",",
"parameters",
":",
"parameters",
")",
"if",
"api_result",
".",
"success?",
"timeline_items",
"=",
"api_result",
".",
"data",
"page_token",
"=",
"nil",
"if",
"timeline_items",
".",
"items",
".",
"empty?",
"if",
"timeline_items",
".",
"items",
".",
"any?",
"@timeline_list",
".",
"concat",
"(",
"timeline_items",
".",
"items",
")",
"page_token",
"=",
"timeline_items",
".",
"next_page_token",
"end",
"else",
"puts",
"\"An error occurred: #{api_result.data['error']['message']}\"",
"page_token",
"=",
"nil",
"end",
"end",
"while",
"page_token",
".",
"to_s",
"!=",
"''",
"timeline_list",
"(",
"opts",
")",
"end"
] | this method is pretty much extracted directly from
the mirror API code samples in ruby
https://developers.google.com/glass/v1/reference/timeline/list | [
"this",
"method",
"is",
"pretty",
"much",
"extracted",
"directly",
"from",
"the",
"mirror",
"API",
"code",
"samples",
"in",
"ruby"
] | a581281a9c5d09ed21ba7369b5b714f1c95d629d | https://github.com/thirst/glass-rails/blob/a581281a9c5d09ed21ba7369b5b714f1c95d629d/lib/glass/client.rb#L135-L157 | train |
zohararad/handlebarer | lib/handlebarer/serialize.rb | Handlebarer.Serialize.to_hbs | def to_hbs
h = {:model => self.class.name.downcase}
self.hbs_attributes.each do |attr|
h[attr] = self.send(attr)
ans = h[attr].class.ancestors
if h[attr].class.respond_to?(:hbs_serializable) || ans.include?(Enumerable) || ans.include?(ActiveModel::Validations)
h[attr] = h[attr].to_hbs
else
end
end
h
end | ruby | def to_hbs
h = {:model => self.class.name.downcase}
self.hbs_attributes.each do |attr|
h[attr] = self.send(attr)
ans = h[attr].class.ancestors
if h[attr].class.respond_to?(:hbs_serializable) || ans.include?(Enumerable) || ans.include?(ActiveModel::Validations)
h[attr] = h[attr].to_hbs
else
end
end
h
end | [
"def",
"to_hbs",
"h",
"=",
"{",
":model",
"=>",
"self",
".",
"class",
".",
"name",
".",
"downcase",
"}",
"self",
".",
"hbs_attributes",
".",
"each",
"do",
"|",
"attr",
"|",
"h",
"[",
"attr",
"]",
"=",
"self",
".",
"send",
"(",
"attr",
")",
"ans",
"=",
"h",
"[",
"attr",
"]",
".",
"class",
".",
"ancestors",
"if",
"h",
"[",
"attr",
"]",
".",
"class",
".",
"respond_to?",
"(",
":hbs_serializable",
")",
"||",
"ans",
".",
"include?",
"(",
"Enumerable",
")",
"||",
"ans",
".",
"include?",
"(",
"ActiveModel",
"::",
"Validations",
")",
"h",
"[",
"attr",
"]",
"=",
"h",
"[",
"attr",
"]",
".",
"to_hbs",
"else",
"end",
"end",
"h",
"end"
] | Serialize instance attributes to a Hash based on serializable attributes defined on Model class.
@return [Hash] hash of model instance attributes | [
"Serialize",
"instance",
"attributes",
"to",
"a",
"Hash",
"based",
"on",
"serializable",
"attributes",
"defined",
"on",
"Model",
"class",
"."
] | f5b2db17cb72fd2874ebe8268cf6f2ae17e74002 | https://github.com/zohararad/handlebarer/blob/f5b2db17cb72fd2874ebe8268cf6f2ae17e74002/lib/handlebarer/serialize.rb#L40-L52 | train |
zohararad/handlebarer | lib/handlebarer/serialize.rb | Handlebarer.Serialize.hbs_attributes | def hbs_attributes
s = self.class.class_variable_get(:@@serialize)
if s[:merge]
attrs = s[:attrs] + self.attributes.keys
else
attrs = s[:attrs]
end
attrs.collect{|attr| attr.to_sym}.uniq
end | ruby | def hbs_attributes
s = self.class.class_variable_get(:@@serialize)
if s[:merge]
attrs = s[:attrs] + self.attributes.keys
else
attrs = s[:attrs]
end
attrs.collect{|attr| attr.to_sym}.uniq
end | [
"def",
"hbs_attributes",
"s",
"=",
"self",
".",
"class",
".",
"class_variable_get",
"(",
":@@serialize",
")",
"if",
"s",
"[",
":merge",
"]",
"attrs",
"=",
"s",
"[",
":attrs",
"]",
"+",
"self",
".",
"attributes",
".",
"keys",
"else",
"attrs",
"=",
"s",
"[",
":attrs",
"]",
"end",
"attrs",
".",
"collect",
"{",
"|",
"attr",
"|",
"attr",
".",
"to_sym",
"}",
".",
"uniq",
"end"
] | List of Model attributes that should be serialized when called `to_hbs` on Model instance
@return [Array] list of serializable attributes | [
"List",
"of",
"Model",
"attributes",
"that",
"should",
"be",
"serialized",
"when",
"called",
"to_hbs",
"on",
"Model",
"instance"
] | f5b2db17cb72fd2874ebe8268cf6f2ae17e74002 | https://github.com/zohararad/handlebarer/blob/f5b2db17cb72fd2874ebe8268cf6f2ae17e74002/lib/handlebarer/serialize.rb#L56-L64 | train |
patchapps/hash-that-tree | lib/compare.rb | HashThatTree.CompareMD5.validate | def validate
if(folder1==nil) || (folder1=="") || !Dir.exists?(folder1)
puts "a valid folder path is required as argument 1"
exit
end
if(folder2==nil) || (folder2=="") || !Dir.exists?(folder2)
puts "a valid folder path is required as argument 2"
exit
end
end | ruby | def validate
if(folder1==nil) || (folder1=="") || !Dir.exists?(folder1)
puts "a valid folder path is required as argument 1"
exit
end
if(folder2==nil) || (folder2=="") || !Dir.exists?(folder2)
puts "a valid folder path is required as argument 2"
exit
end
end | [
"def",
"validate",
"if",
"(",
"folder1",
"==",
"nil",
")",
"||",
"(",
"folder1",
"==",
"\"\"",
")",
"||",
"!",
"Dir",
".",
"exists?",
"(",
"folder1",
")",
"puts",
"\"a valid folder path is required as argument 1\"",
"exit",
"end",
"if",
"(",
"folder2",
"==",
"nil",
")",
"||",
"(",
"folder2",
"==",
"\"\"",
")",
"||",
"!",
"Dir",
".",
"exists?",
"(",
"folder2",
")",
"puts",
"\"a valid folder path is required as argument 2\"",
"exit",
"end",
"end"
] | the format to output the results to. csv, html or json
initialize the class with the folders to be compared
Validates the input ensuring the arguments are both valid folders | [
"the",
"format",
"to",
"output",
"the",
"results",
"to",
".",
"csv",
"html",
"or",
"json",
"initialize",
"the",
"class",
"with",
"the",
"folders",
"to",
"be",
"compared",
"Validates",
"the",
"input",
"ensuring",
"the",
"arguments",
"are",
"both",
"valid",
"folders"
] | 05a006389340d96d13613abc60a16f83b2bfd052 | https://github.com/patchapps/hash-that-tree/blob/05a006389340d96d13613abc60a16f83b2bfd052/lib/compare.rb#L28-L39 | train |
patchapps/hash-that-tree | lib/compare.rb | HashThatTree.CompareMD5.display_results_html | def display_results_html
output ="<!DOCTYPE html><html xmlns=\"http://www.w3.org/1999/xhtml\"><head><title></title></head><body>"
output.concat("<table><thead><tr><td>FileName</td></tr><tr><td>#{@folder1}</td></tr><tr><td>#{@folder2}</td></tr><tr><td>Equal</td></tr></thead>")
@filehash.each{ |key, value| output.concat("<tbody><tr><td>#{value.file_name}</td></tr><tr><td>#{value.file_hash1}</td></tr><tr><td>#{value.file_hash2}</td></tr><tr><td>#{value.file_hash1==value.file_hash2}</td></tr>")}
output.concat("</tbody></table></body></html>")
puts output
end | ruby | def display_results_html
output ="<!DOCTYPE html><html xmlns=\"http://www.w3.org/1999/xhtml\"><head><title></title></head><body>"
output.concat("<table><thead><tr><td>FileName</td></tr><tr><td>#{@folder1}</td></tr><tr><td>#{@folder2}</td></tr><tr><td>Equal</td></tr></thead>")
@filehash.each{ |key, value| output.concat("<tbody><tr><td>#{value.file_name}</td></tr><tr><td>#{value.file_hash1}</td></tr><tr><td>#{value.file_hash2}</td></tr><tr><td>#{value.file_hash1==value.file_hash2}</td></tr>")}
output.concat("</tbody></table></body></html>")
puts output
end | [
"def",
"display_results_html",
"output",
"=",
"\"<!DOCTYPE html><html xmlns=\\\"http://www.w3.org/1999/xhtml\\\"><head><title></title></head><body>\"",
"output",
".",
"concat",
"(",
"\"<table><thead><tr><td>FileName</td></tr><tr><td>#{@folder1}</td></tr><tr><td>#{@folder2}</td></tr><tr><td>Equal</td></tr></thead>\"",
")",
"@filehash",
".",
"each",
"{",
"|",
"key",
",",
"value",
"|",
"output",
".",
"concat",
"(",
"\"<tbody><tr><td>#{value.file_name}</td></tr><tr><td>#{value.file_hash1}</td></tr><tr><td>#{value.file_hash2}</td></tr><tr><td>#{value.file_hash1==value.file_hash2}</td></tr>\"",
")",
"}",
"output",
".",
"concat",
"(",
"\"</tbody></table></body></html>\"",
")",
"puts",
"output",
"end"
] | Prints the results to standard out in the csv format specified. | [
"Prints",
"the",
"results",
"to",
"standard",
"out",
"in",
"the",
"csv",
"format",
"specified",
"."
] | 05a006389340d96d13613abc60a16f83b2bfd052 | https://github.com/patchapps/hash-that-tree/blob/05a006389340d96d13613abc60a16f83b2bfd052/lib/compare.rb#L96-L102 | train |
plexus/analects | lib/analects/encoding.rb | Analects.Encoding.ratings | def ratings(str)
all_valid_cjk(str).map do |enc|
[
enc,
recode(enc, str).codepoints.map do |point|
Analects::Models::Zi.codepoint_ranges.map.with_index do |range, idx|
next 6 - idx if range.include?(point)
0
end.inject(:+)
end.inject(:+)
]
end.sort_by(&:last).reverse
end | ruby | def ratings(str)
all_valid_cjk(str).map do |enc|
[
enc,
recode(enc, str).codepoints.map do |point|
Analects::Models::Zi.codepoint_ranges.map.with_index do |range, idx|
next 6 - idx if range.include?(point)
0
end.inject(:+)
end.inject(:+)
]
end.sort_by(&:last).reverse
end | [
"def",
"ratings",
"(",
"str",
")",
"all_valid_cjk",
"(",
"str",
")",
".",
"map",
"do",
"|",
"enc",
"|",
"[",
"enc",
",",
"recode",
"(",
"enc",
",",
"str",
")",
".",
"codepoints",
".",
"map",
"do",
"|",
"point",
"|",
"Analects",
"::",
"Models",
"::",
"Zi",
".",
"codepoint_ranges",
".",
"map",
".",
"with_index",
"do",
"|",
"range",
",",
"idx",
"|",
"next",
"6",
"-",
"idx",
"if",
"range",
".",
"include?",
"(",
"point",
")",
"0",
"end",
".",
"inject",
"(",
":+",
")",
"end",
".",
"inject",
"(",
":+",
")",
"]",
"end",
".",
"sort_by",
"(",
":last",
")",
".",
"reverse",
"end"
] | Crude way to guess which encoding it is | [
"Crude",
"way",
"to",
"guess",
"which",
"encoding",
"it",
"is"
] | 3ef5c9b54b5d31fd1c3b7143f9e5e4ae40185dd9 | https://github.com/plexus/analects/blob/3ef5c9b54b5d31fd1c3b7143f9e5e4ae40185dd9/lib/analects/encoding.rb#L34-L46 | train |
ecssiah/project-euler-cli | lib/project_euler_cli/concerns/scraper.rb | ProjectEulerCli.Scraper.lookup_totals | def lookup_totals
begin
Timeout.timeout(4) do
html = open("https://projecteuler.net/recent")
fragment = Nokogiri::HTML(html)
id_col = fragment.css('#problems_table td.id_column')
# The newest problem is the first one listed on the recent page. The ID
# of this problem will always equal the total number of problems.
id_col.first.text.to_i.times { Problem.new }
# There are ten problems on the recent page, so the last archive problem
# can be found by subtracting 10 from the total number of problems.
Page.total = Problem.page(Problem.total - 10)
end
rescue Timeout::Error
puts "Project Euler is not responding."
exit(true)
end
end | ruby | def lookup_totals
begin
Timeout.timeout(4) do
html = open("https://projecteuler.net/recent")
fragment = Nokogiri::HTML(html)
id_col = fragment.css('#problems_table td.id_column')
# The newest problem is the first one listed on the recent page. The ID
# of this problem will always equal the total number of problems.
id_col.first.text.to_i.times { Problem.new }
# There are ten problems on the recent page, so the last archive problem
# can be found by subtracting 10 from the total number of problems.
Page.total = Problem.page(Problem.total - 10)
end
rescue Timeout::Error
puts "Project Euler is not responding."
exit(true)
end
end | [
"def",
"lookup_totals",
"begin",
"Timeout",
".",
"timeout",
"(",
"4",
")",
"do",
"html",
"=",
"open",
"(",
"\"https://projecteuler.net/recent\"",
")",
"fragment",
"=",
"Nokogiri",
"::",
"HTML",
"(",
"html",
")",
"id_col",
"=",
"fragment",
".",
"css",
"(",
"'#problems_table td.id_column'",
")",
"# The newest problem is the first one listed on the recent page. The ID ",
"# of this problem will always equal the total number of problems.",
"id_col",
".",
"first",
".",
"text",
".",
"to_i",
".",
"times",
"{",
"Problem",
".",
"new",
"}",
"# There are ten problems on the recent page, so the last archive problem ",
"# can be found by subtracting 10 from the total number of problems.",
"Page",
".",
"total",
"=",
"Problem",
".",
"page",
"(",
"Problem",
".",
"total",
"-",
"10",
")",
"end",
"rescue",
"Timeout",
"::",
"Error",
"puts",
"\"Project Euler is not responding.\"",
"exit",
"(",
"true",
")",
"end",
"end"
] | Pulls information from the recent page to determine the total number of
problems and pages. | [
"Pulls",
"information",
"from",
"the",
"recent",
"page",
"to",
"determine",
"the",
"total",
"number",
"of",
"problems",
"and",
"pages",
"."
] | ae6fb1fb516bd9bcf193e3e1f1c82894198fe997 | https://github.com/ecssiah/project-euler-cli/blob/ae6fb1fb516bd9bcf193e3e1f1c82894198fe997/lib/project_euler_cli/concerns/scraper.rb#L8-L28 | train |
ecssiah/project-euler-cli | lib/project_euler_cli/concerns/scraper.rb | ProjectEulerCli.Scraper.load_recent | def load_recent
return if Page.visited.include?(0)
html = open("https://projecteuler.net/recent")
fragment = Nokogiri::HTML(html)
problem_links = fragment.css('#problems_table td a')
i = Problem.total
problem_links.each do |link|
Problem[i].title = link.text
i -= 1
end
Page.visited << 0
end | ruby | def load_recent
return if Page.visited.include?(0)
html = open("https://projecteuler.net/recent")
fragment = Nokogiri::HTML(html)
problem_links = fragment.css('#problems_table td a')
i = Problem.total
problem_links.each do |link|
Problem[i].title = link.text
i -= 1
end
Page.visited << 0
end | [
"def",
"load_recent",
"return",
"if",
"Page",
".",
"visited",
".",
"include?",
"(",
"0",
")",
"html",
"=",
"open",
"(",
"\"https://projecteuler.net/recent\"",
")",
"fragment",
"=",
"Nokogiri",
"::",
"HTML",
"(",
"html",
")",
"problem_links",
"=",
"fragment",
".",
"css",
"(",
"'#problems_table td a'",
")",
"i",
"=",
"Problem",
".",
"total",
"problem_links",
".",
"each",
"do",
"|",
"link",
"|",
"Problem",
"[",
"i",
"]",
".",
"title",
"=",
"link",
".",
"text",
"i",
"-=",
"1",
"end",
"Page",
".",
"visited",
"<<",
"0",
"end"
] | Loads in all of the problem numbers and titles from the recent page. | [
"Loads",
"in",
"all",
"of",
"the",
"problem",
"numbers",
"and",
"titles",
"from",
"the",
"recent",
"page",
"."
] | ae6fb1fb516bd9bcf193e3e1f1c82894198fe997 | https://github.com/ecssiah/project-euler-cli/blob/ae6fb1fb516bd9bcf193e3e1f1c82894198fe997/lib/project_euler_cli/concerns/scraper.rb#L31-L46 | train |
ecssiah/project-euler-cli | lib/project_euler_cli/concerns/scraper.rb | ProjectEulerCli.Scraper.load_page | def load_page(page)
return if Page.visited.include?(page)
html = open("https://projecteuler.net/archives;page=#{page}")
fragment = Nokogiri::HTML(html)
problem_links = fragment.css('#problems_table td a')
i = (page - 1) * Page::LENGTH + 1
problem_links.each do |link|
Problem[i].title = link.text
i += 1
end
Page.visited << page
end | ruby | def load_page(page)
return if Page.visited.include?(page)
html = open("https://projecteuler.net/archives;page=#{page}")
fragment = Nokogiri::HTML(html)
problem_links = fragment.css('#problems_table td a')
i = (page - 1) * Page::LENGTH + 1
problem_links.each do |link|
Problem[i].title = link.text
i += 1
end
Page.visited << page
end | [
"def",
"load_page",
"(",
"page",
")",
"return",
"if",
"Page",
".",
"visited",
".",
"include?",
"(",
"page",
")",
"html",
"=",
"open",
"(",
"\"https://projecteuler.net/archives;page=#{page}\"",
")",
"fragment",
"=",
"Nokogiri",
"::",
"HTML",
"(",
"html",
")",
"problem_links",
"=",
"fragment",
".",
"css",
"(",
"'#problems_table td a'",
")",
"i",
"=",
"(",
"page",
"-",
"1",
")",
"*",
"Page",
"::",
"LENGTH",
"+",
"1",
"problem_links",
".",
"each",
"do",
"|",
"link",
"|",
"Problem",
"[",
"i",
"]",
".",
"title",
"=",
"link",
".",
"text",
"i",
"+=",
"1",
"end",
"Page",
".",
"visited",
"<<",
"page",
"end"
] | Loads the problem numbers and titles for an individual page of the archive. | [
"Loads",
"the",
"problem",
"numbers",
"and",
"titles",
"for",
"an",
"individual",
"page",
"of",
"the",
"archive",
"."
] | ae6fb1fb516bd9bcf193e3e1f1c82894198fe997 | https://github.com/ecssiah/project-euler-cli/blob/ae6fb1fb516bd9bcf193e3e1f1c82894198fe997/lib/project_euler_cli/concerns/scraper.rb#L49-L64 | train |
ecssiah/project-euler-cli | lib/project_euler_cli/concerns/scraper.rb | ProjectEulerCli.Scraper.load_problem_details | def load_problem_details(id)
return unless Problem[id].published.nil?
html = open("https://projecteuler.net/problem=#{id}")
fragment = Nokogiri::HTML(html)
problem_info = fragment.css('div#problem_info span span')
details = problem_info.text.split(';')
Problem[id].published = details[0].strip
Problem[id].solved_by = details[1].strip
# recent problems do not have a difficult rating
Problem[id].difficulty = details[2].strip if id <= Problem.total - 10
end | ruby | def load_problem_details(id)
return unless Problem[id].published.nil?
html = open("https://projecteuler.net/problem=#{id}")
fragment = Nokogiri::HTML(html)
problem_info = fragment.css('div#problem_info span span')
details = problem_info.text.split(';')
Problem[id].published = details[0].strip
Problem[id].solved_by = details[1].strip
# recent problems do not have a difficult rating
Problem[id].difficulty = details[2].strip if id <= Problem.total - 10
end | [
"def",
"load_problem_details",
"(",
"id",
")",
"return",
"unless",
"Problem",
"[",
"id",
"]",
".",
"published",
".",
"nil?",
"html",
"=",
"open",
"(",
"\"https://projecteuler.net/problem=#{id}\"",
")",
"fragment",
"=",
"Nokogiri",
"::",
"HTML",
"(",
"html",
")",
"problem_info",
"=",
"fragment",
".",
"css",
"(",
"'div#problem_info span span'",
")",
"details",
"=",
"problem_info",
".",
"text",
".",
"split",
"(",
"';'",
")",
"Problem",
"[",
"id",
"]",
".",
"published",
"=",
"details",
"[",
"0",
"]",
".",
"strip",
"Problem",
"[",
"id",
"]",
".",
"solved_by",
"=",
"details",
"[",
"1",
"]",
".",
"strip",
"# recent problems do not have a difficult rating",
"Problem",
"[",
"id",
"]",
".",
"difficulty",
"=",
"details",
"[",
"2",
"]",
".",
"strip",
"if",
"id",
"<=",
"Problem",
".",
"total",
"-",
"10",
"end"
] | Loads the details of an individual problem. | [
"Loads",
"the",
"details",
"of",
"an",
"individual",
"problem",
"."
] | ae6fb1fb516bd9bcf193e3e1f1c82894198fe997 | https://github.com/ecssiah/project-euler-cli/blob/ae6fb1fb516bd9bcf193e3e1f1c82894198fe997/lib/project_euler_cli/concerns/scraper.rb#L67-L81 | train |
pwnall/authpwn_rails | lib/authpwn_rails/session_mailer.rb | Authpwn.SessionMailer.email_verification_email | def email_verification_email(token, root_url)
@token = token
@protocol, @host = *root_url.split('://', 2)
@host.slice!(-1) if @host[-1] == ?/
hostname = @host.split(':', 2).first # Strip out any port.
mail to: @token.email,
subject: email_verification_subject(token, hostname, @protocol),
from: email_verification_from(token, hostname, @protocol)
end | ruby | def email_verification_email(token, root_url)
@token = token
@protocol, @host = *root_url.split('://', 2)
@host.slice!(-1) if @host[-1] == ?/
hostname = @host.split(':', 2).first # Strip out any port.
mail to: @token.email,
subject: email_verification_subject(token, hostname, @protocol),
from: email_verification_from(token, hostname, @protocol)
end | [
"def",
"email_verification_email",
"(",
"token",
",",
"root_url",
")",
"@token",
"=",
"token",
"@protocol",
",",
"@host",
"=",
"root_url",
".",
"split",
"(",
"'://'",
",",
"2",
")",
"@host",
".",
"slice!",
"(",
"-",
"1",
")",
"if",
"@host",
"[",
"-",
"1",
"]",
"==",
"?/",
"hostname",
"=",
"@host",
".",
"split",
"(",
"':'",
",",
"2",
")",
".",
"first",
"# Strip out any port.",
"mail",
"to",
":",
"@token",
".",
"email",
",",
"subject",
":",
"email_verification_subject",
"(",
"token",
",",
"hostname",
",",
"@protocol",
")",
",",
"from",
":",
"email_verification_from",
"(",
"token",
",",
"hostname",
",",
"@protocol",
")",
"end"
] | Creates an e-mail containing a verification token for the e-mail address.
@param [String] token the e-mail confirmation token
@param [String] the application's root URL (e.g. "https://localhost:3000/") | [
"Creates",
"an",
"e",
"-",
"mail",
"containing",
"a",
"verification",
"token",
"for",
"the",
"e",
"-",
"mail",
"address",
"."
] | de3bd612a00025e8dc8296a73abe3acba948db17 | https://github.com/pwnall/authpwn_rails/blob/de3bd612a00025e8dc8296a73abe3acba948db17/lib/authpwn_rails/session_mailer.rb#L12-L21 | train |
pwnall/authpwn_rails | lib/authpwn_rails/session_mailer.rb | Authpwn.SessionMailer.reset_password_email | def reset_password_email(email, token, root_url)
@email, @token, @host, @protocol = email, token
@token = token
@protocol, @host = *root_url.split('://', 2)
@host.slice!(-1) if @host[-1] == ?/
hostname = @host.split(':', 2).first # Strip out any port.
mail to: email, from: reset_password_from(token, hostname, @protocol),
subject: reset_password_subject(token, hostname, @protocol)
end | ruby | def reset_password_email(email, token, root_url)
@email, @token, @host, @protocol = email, token
@token = token
@protocol, @host = *root_url.split('://', 2)
@host.slice!(-1) if @host[-1] == ?/
hostname = @host.split(':', 2).first # Strip out any port.
mail to: email, from: reset_password_from(token, hostname, @protocol),
subject: reset_password_subject(token, hostname, @protocol)
end | [
"def",
"reset_password_email",
"(",
"email",
",",
"token",
",",
"root_url",
")",
"@email",
",",
"@token",
",",
"@host",
",",
"@protocol",
"=",
"email",
",",
"token",
"@token",
"=",
"token",
"@protocol",
",",
"@host",
"=",
"root_url",
".",
"split",
"(",
"'://'",
",",
"2",
")",
"@host",
".",
"slice!",
"(",
"-",
"1",
")",
"if",
"@host",
"[",
"-",
"1",
"]",
"==",
"?/",
"hostname",
"=",
"@host",
".",
"split",
"(",
"':'",
",",
"2",
")",
".",
"first",
"# Strip out any port.",
"mail",
"to",
":",
"email",
",",
"from",
":",
"reset_password_from",
"(",
"token",
",",
"hostname",
",",
"@protocol",
")",
",",
"subject",
":",
"reset_password_subject",
"(",
"token",
",",
"hostname",
",",
"@protocol",
")",
"end"
] | Creates an e-mail containing a password reset token.
@param [String] email the email to send the token to
@param [String] token the password reset token
@param [String] root_url the application's root URL
(e.g. "https://localhost:3000/") | [
"Creates",
"an",
"e",
"-",
"mail",
"containing",
"a",
"password",
"reset",
"token",
"."
] | de3bd612a00025e8dc8296a73abe3acba948db17 | https://github.com/pwnall/authpwn_rails/blob/de3bd612a00025e8dc8296a73abe3acba948db17/lib/authpwn_rails/session_mailer.rb#L43-L52 | train |
djlebersilvestre/descendants-loader | lib/descendants_loader.rb | DescendantsLoader.ClassMethods.load_self_descendants | def load_self_descendants
file = ClassFinder.where_is(self)
path = File.expand_path(File.dirname(file))
Dir["#{path}/**/*.rb"].each { |f| load f }
end | ruby | def load_self_descendants
file = ClassFinder.where_is(self)
path = File.expand_path(File.dirname(file))
Dir["#{path}/**/*.rb"].each { |f| load f }
end | [
"def",
"load_self_descendants",
"file",
"=",
"ClassFinder",
".",
"where_is",
"(",
"self",
")",
"path",
"=",
"File",
".",
"expand_path",
"(",
"File",
".",
"dirname",
"(",
"file",
")",
")",
"Dir",
"[",
"\"#{path}/**/*.rb\"",
"]",
".",
"each",
"{",
"|",
"f",
"|",
"load",
"f",
"}",
"end"
] | Find and load all ruby files under the same directory structure
of the declared class which is including DescendantsLoader module.
This is the trick to put the classes into ObjectSpace and have the
desired behavior of Object.descendants and Object.subclasses. | [
"Find",
"and",
"load",
"all",
"ruby",
"files",
"under",
"the",
"same",
"directory",
"structure",
"of",
"the",
"declared",
"class",
"which",
"is",
"including",
"DescendantsLoader",
"module",
"."
] | 5b1fe23b1de3e6d62d20d46f79a80c132d0b165f | https://github.com/djlebersilvestre/descendants-loader/blob/5b1fe23b1de3e6d62d20d46f79a80c132d0b165f/lib/descendants_loader.rb#L64-L68 | train |
ratherblue/renegade | lib/renegade/commit_message.rb | Renegade.CommitMessage.check_commit_message_length | def check_commit_message_length(message)
check_label = 'Commit message length'
if message.length >= @min_length && message.length <= @max_length
Status.report(check_label, true)
else
@errors.push "Commit messages should be between #{@min_length} "\
"and #{@max_length} characters."
Status.report(check_label, false)
end
end | ruby | def check_commit_message_length(message)
check_label = 'Commit message length'
if message.length >= @min_length && message.length <= @max_length
Status.report(check_label, true)
else
@errors.push "Commit messages should be between #{@min_length} "\
"and #{@max_length} characters."
Status.report(check_label, false)
end
end | [
"def",
"check_commit_message_length",
"(",
"message",
")",
"check_label",
"=",
"'Commit message length'",
"if",
"message",
".",
"length",
">=",
"@min_length",
"&&",
"message",
".",
"length",
"<=",
"@max_length",
"Status",
".",
"report",
"(",
"check_label",
",",
"true",
")",
"else",
"@errors",
".",
"push",
"\"Commit messages should be between #{@min_length} \"",
"\"and #{@max_length} characters.\"",
"Status",
".",
"report",
"(",
"check_label",
",",
"false",
")",
"end",
"end"
] | Check message length | [
"Check",
"message",
"length"
] | b058750979c4510835368fb0dba552e228331a8c | https://github.com/ratherblue/renegade/blob/b058750979c4510835368fb0dba552e228331a8c/lib/renegade/commit_message.rb#L25-L35 | train |
jeremyvdw/disqussion | lib/disqussion/client/users.rb | Disqussion.Users.follow | def follow(*args)
options = args.last.is_a?(Hash) ? args.pop : {}
target = args.first
merge_target_into_options!(target, options)
response = post('users/follow', options)
end | ruby | def follow(*args)
options = args.last.is_a?(Hash) ? args.pop : {}
target = args.first
merge_target_into_options!(target, options)
response = post('users/follow', options)
end | [
"def",
"follow",
"(",
"*",
"args",
")",
"options",
"=",
"args",
".",
"last",
".",
"is_a?",
"(",
"Hash",
")",
"?",
"args",
".",
"pop",
":",
"{",
"}",
"target",
"=",
"args",
".",
"first",
"merge_target_into_options!",
"(",
"target",
",",
"options",
")",
"response",
"=",
"post",
"(",
"'users/follow'",
",",
"options",
")",
"end"
] | Follow a user
@accessibility: public key, secret key
@methods: POST
@format: json, jsonp
@authenticated: true
@limited: false
@param target [Integer, String] A Disqus user ID or screen name.
@return [Hashie::Rash] Details on the requested user.
@example Return extended information for 'the88'
Disqussion::Client.follow("the88")
Disqussion::Client.follow(1234) # Same as above
@see: http://disqus.com/api/3.0/users/details.json | [
"Follow",
"a",
"user"
] | 5ad1b0325b7630daf41eb59fc8acbcb785cbc387 | https://github.com/jeremyvdw/disqussion/blob/5ad1b0325b7630daf41eb59fc8acbcb785cbc387/lib/disqussion/client/users.rb#L51-L56 | train |
jeremyruppel/codependency | lib/codependency/parser.rb | Codependency.Parser.parse | def parse( file )
pattern = PATTERNS[ File.extname( file ) ]
IO.readlines( file ).take_while do |line|
line =~ pattern
end.map { |line| line[ pattern, 1 ] }
end | ruby | def parse( file )
pattern = PATTERNS[ File.extname( file ) ]
IO.readlines( file ).take_while do |line|
line =~ pattern
end.map { |line| line[ pattern, 1 ] }
end | [
"def",
"parse",
"(",
"file",
")",
"pattern",
"=",
"PATTERNS",
"[",
"File",
".",
"extname",
"(",
"file",
")",
"]",
"IO",
".",
"readlines",
"(",
"file",
")",
".",
"take_while",
"do",
"|",
"line",
"|",
"line",
"=~",
"pattern",
"end",
".",
"map",
"{",
"|",
"line",
"|",
"line",
"[",
"pattern",
",",
"1",
"]",
"}",
"end"
] | Determines a file's dependencies based on the file's extension. | [
"Determines",
"a",
"file",
"s",
"dependencies",
"based",
"on",
"the",
"file",
"s",
"extension",
"."
] | 635eddcc0149211e71f89bcaddaa6603aacf942f | https://github.com/jeremyruppel/codependency/blob/635eddcc0149211e71f89bcaddaa6603aacf942f/lib/codependency/parser.rb#L12-L18 | train |
octoai/gem-octocore-cassandra | lib/octocore-cassandra/counter.rb | Octo.Counter.increment_for | def increment_for(obj)
# decide the time of event asap
ts = Time.now.ceil.to_i
if obj.class.ancestors.include?Cequel::Record
args = obj.key_attributes.collect { |k,v| v.to_s }
cache_key = generate_key(ts, obj.class.name, *args)
val = Cequel::Record.redis.get(cache_key)
if val.nil?
val = 1
else
val = val.to_i + 1
end
ttl = (time_window + 1) * 60
# Update a sharded counter
Cequel::Record.redis.setex(cache_key, ttl, val)
# Optionally, update the index
index_key = generate_index_key(ts, obj.class.name, *args)
index_present = Cequel::Record.redis.get(index_key).try(:to_i)
if index_present != 1
Cequel::Record.redis.setex(index_key, ttl, 1)
end
end
end | ruby | def increment_for(obj)
# decide the time of event asap
ts = Time.now.ceil.to_i
if obj.class.ancestors.include?Cequel::Record
args = obj.key_attributes.collect { |k,v| v.to_s }
cache_key = generate_key(ts, obj.class.name, *args)
val = Cequel::Record.redis.get(cache_key)
if val.nil?
val = 1
else
val = val.to_i + 1
end
ttl = (time_window + 1) * 60
# Update a sharded counter
Cequel::Record.redis.setex(cache_key, ttl, val)
# Optionally, update the index
index_key = generate_index_key(ts, obj.class.name, *args)
index_present = Cequel::Record.redis.get(index_key).try(:to_i)
if index_present != 1
Cequel::Record.redis.setex(index_key, ttl, 1)
end
end
end | [
"def",
"increment_for",
"(",
"obj",
")",
"# decide the time of event asap",
"ts",
"=",
"Time",
".",
"now",
".",
"ceil",
".",
"to_i",
"if",
"obj",
".",
"class",
".",
"ancestors",
".",
"include?",
"Cequel",
"::",
"Record",
"args",
"=",
"obj",
".",
"key_attributes",
".",
"collect",
"{",
"|",
"k",
",",
"v",
"|",
"v",
".",
"to_s",
"}",
"cache_key",
"=",
"generate_key",
"(",
"ts",
",",
"obj",
".",
"class",
".",
"name",
",",
"args",
")",
"val",
"=",
"Cequel",
"::",
"Record",
".",
"redis",
".",
"get",
"(",
"cache_key",
")",
"if",
"val",
".",
"nil?",
"val",
"=",
"1",
"else",
"val",
"=",
"val",
".",
"to_i",
"+",
"1",
"end",
"ttl",
"=",
"(",
"time_window",
"+",
"1",
")",
"*",
"60",
"# Update a sharded counter",
"Cequel",
"::",
"Record",
".",
"redis",
".",
"setex",
"(",
"cache_key",
",",
"ttl",
",",
"val",
")",
"# Optionally, update the index",
"index_key",
"=",
"generate_index_key",
"(",
"ts",
",",
"obj",
".",
"class",
".",
"name",
",",
"args",
")",
"index_present",
"=",
"Cequel",
"::",
"Record",
".",
"redis",
".",
"get",
"(",
"index_key",
")",
".",
"try",
"(",
":to_i",
")",
"if",
"index_present",
"!=",
"1",
"Cequel",
"::",
"Record",
".",
"redis",
".",
"setex",
"(",
"index_key",
",",
"ttl",
",",
"1",
")",
"end",
"end",
"end"
] | Increments the counter for a model.
@param [Object] obj The model instance for whom counter would be
incremented | [
"Increments",
"the",
"counter",
"for",
"a",
"model",
"."
] | c0977dce5ba0eb174ff810f161aba151069935df | https://github.com/octoai/gem-octocore-cassandra/blob/c0977dce5ba0eb174ff810f161aba151069935df/lib/octocore-cassandra/counter.rb#L53-L81 | train |
octoai/gem-octocore-cassandra | lib/octocore-cassandra/counter.rb | Octo.Counter.aggregate | def aggregate(ts = Time.now.floor)
ts = ts.to_i
aggr = {}
# Find all counters from the index
index_key = generate_index_key(ts, '*')
counters = Cequel::Record.redis.keys(index_key)
counters.each do |cnt|
_tmp = cnt.split(SEPARATOR)
_ts = _tmp[2].to_i
aggr[_ts] = {} unless aggr.has_key?(_ts)
clazz = _tmp[3]
_clazz = clazz.constantize
_attrs = _tmp[4.._tmp.length]
args = {}
_clazz.key_column_names.each_with_index do |k, i|
args[k] = _attrs[i]
end
obj = _clazz.public_send(:get_cached, args)
# construct the keys for all counters matching this patter
_attrs << '*'
counters_search_key = generate_key_prefix(_ts, clazz, _attrs)
counter_keys = Cequel::Record.redis.keys(counters_search_key)
counter_keys.each do |c_key|
val = Cequel::Record.redis.get(c_key)
if val
aggr[_ts][obj] = aggr[_ts].fetch(obj, 0) + val.to_i
else
aggr[_ts][obj] = aggr[_ts].fetch(obj, 0) + 1
end
end
end
aggr
end | ruby | def aggregate(ts = Time.now.floor)
ts = ts.to_i
aggr = {}
# Find all counters from the index
index_key = generate_index_key(ts, '*')
counters = Cequel::Record.redis.keys(index_key)
counters.each do |cnt|
_tmp = cnt.split(SEPARATOR)
_ts = _tmp[2].to_i
aggr[_ts] = {} unless aggr.has_key?(_ts)
clazz = _tmp[3]
_clazz = clazz.constantize
_attrs = _tmp[4.._tmp.length]
args = {}
_clazz.key_column_names.each_with_index do |k, i|
args[k] = _attrs[i]
end
obj = _clazz.public_send(:get_cached, args)
# construct the keys for all counters matching this patter
_attrs << '*'
counters_search_key = generate_key_prefix(_ts, clazz, _attrs)
counter_keys = Cequel::Record.redis.keys(counters_search_key)
counter_keys.each do |c_key|
val = Cequel::Record.redis.get(c_key)
if val
aggr[_ts][obj] = aggr[_ts].fetch(obj, 0) + val.to_i
else
aggr[_ts][obj] = aggr[_ts].fetch(obj, 0) + 1
end
end
end
aggr
end | [
"def",
"aggregate",
"(",
"ts",
"=",
"Time",
".",
"now",
".",
"floor",
")",
"ts",
"=",
"ts",
".",
"to_i",
"aggr",
"=",
"{",
"}",
"# Find all counters from the index",
"index_key",
"=",
"generate_index_key",
"(",
"ts",
",",
"'*'",
")",
"counters",
"=",
"Cequel",
"::",
"Record",
".",
"redis",
".",
"keys",
"(",
"index_key",
")",
"counters",
".",
"each",
"do",
"|",
"cnt",
"|",
"_tmp",
"=",
"cnt",
".",
"split",
"(",
"SEPARATOR",
")",
"_ts",
"=",
"_tmp",
"[",
"2",
"]",
".",
"to_i",
"aggr",
"[",
"_ts",
"]",
"=",
"{",
"}",
"unless",
"aggr",
".",
"has_key?",
"(",
"_ts",
")",
"clazz",
"=",
"_tmp",
"[",
"3",
"]",
"_clazz",
"=",
"clazz",
".",
"constantize",
"_attrs",
"=",
"_tmp",
"[",
"4",
"..",
"_tmp",
".",
"length",
"]",
"args",
"=",
"{",
"}",
"_clazz",
".",
"key_column_names",
".",
"each_with_index",
"do",
"|",
"k",
",",
"i",
"|",
"args",
"[",
"k",
"]",
"=",
"_attrs",
"[",
"i",
"]",
"end",
"obj",
"=",
"_clazz",
".",
"public_send",
"(",
":get_cached",
",",
"args",
")",
"# construct the keys for all counters matching this patter",
"_attrs",
"<<",
"'*'",
"counters_search_key",
"=",
"generate_key_prefix",
"(",
"_ts",
",",
"clazz",
",",
"_attrs",
")",
"counter_keys",
"=",
"Cequel",
"::",
"Record",
".",
"redis",
".",
"keys",
"(",
"counters_search_key",
")",
"counter_keys",
".",
"each",
"do",
"|",
"c_key",
"|",
"val",
"=",
"Cequel",
"::",
"Record",
".",
"redis",
".",
"get",
"(",
"c_key",
")",
"if",
"val",
"aggr",
"[",
"_ts",
"]",
"[",
"obj",
"]",
"=",
"aggr",
"[",
"_ts",
"]",
".",
"fetch",
"(",
"obj",
",",
"0",
")",
"+",
"val",
".",
"to_i",
"else",
"aggr",
"[",
"_ts",
"]",
"[",
"obj",
"]",
"=",
"aggr",
"[",
"_ts",
"]",
".",
"fetch",
"(",
"obj",
",",
"0",
")",
"+",
"1",
"end",
"end",
"end",
"aggr",
"end"
] | Aggregates all the counters available. Aggregation of only time specific
events can be done by passing the `ts` parameter.
@param [Time] ts The time at which aggregation has to be done.
@return [Hash{Fixnum => Hash{ Obj => Fixnum }}] The counts of each object | [
"Aggregates",
"all",
"the",
"counters",
"available",
".",
"Aggregation",
"of",
"only",
"time",
"specific",
"events",
"can",
"be",
"done",
"by",
"passing",
"the",
"ts",
"parameter",
"."
] | c0977dce5ba0eb174ff810f161aba151069935df | https://github.com/octoai/gem-octocore-cassandra/blob/c0977dce5ba0eb174ff810f161aba151069935df/lib/octocore-cassandra/counter.rb#L164-L202 | train |
SpeciesFileGroup/taxonifi | lib/taxonifi/model/name.rb | Taxonifi.Model::Name.rank= | def rank=(value)
r = value.to_s.downcase.strip
if !RANKS.include?(r)
raise NameError, "#{r} is not a valid rank."
end
@rank = r
end | ruby | def rank=(value)
r = value.to_s.downcase.strip
if !RANKS.include?(r)
raise NameError, "#{r} is not a valid rank."
end
@rank = r
end | [
"def",
"rank",
"=",
"(",
"value",
")",
"r",
"=",
"value",
".",
"to_s",
".",
"downcase",
".",
"strip",
"if",
"!",
"RANKS",
".",
"include?",
"(",
"r",
")",
"raise",
"NameError",
",",
"\"#{r} is not a valid rank.\"",
"end",
"@rank",
"=",
"r",
"end"
] | Set the rank. | [
"Set",
"the",
"rank",
"."
] | 100dc94e7ffd378f6a81381c13768e35b2b65bf2 | https://github.com/SpeciesFileGroup/taxonifi/blob/100dc94e7ffd378f6a81381c13768e35b2b65bf2/lib/taxonifi/model/name.rb#L77-L83 | train |
SpeciesFileGroup/taxonifi | lib/taxonifi/model/name.rb | Taxonifi.Model::IcznName.name= | def name=(name)
case @rank
when 'superfamily'
raise NameError, "ICZN superfamily name does not end in 'oidae'." if name[-5,5] != 'oidae'
when 'family'
raise NameError, "ICZN family name does not end in 'idae'." if name[-4,4] != 'idae'
when 'subfamily'
raise NameError, "ICZN subfamily name does not end in 'inae'." if name[-4,4] != 'inae'
when 'tribe'
raise NameError, "ICZN tribe name does not end in 'ini'." if name[-3,3] != 'ini'
when 'subtribe'
raise NameError, "ICZN subtribe name does not end in 'ina'." if name[-3,3] != 'ina'
end
@name = name
end | ruby | def name=(name)
case @rank
when 'superfamily'
raise NameError, "ICZN superfamily name does not end in 'oidae'." if name[-5,5] != 'oidae'
when 'family'
raise NameError, "ICZN family name does not end in 'idae'." if name[-4,4] != 'idae'
when 'subfamily'
raise NameError, "ICZN subfamily name does not end in 'inae'." if name[-4,4] != 'inae'
when 'tribe'
raise NameError, "ICZN tribe name does not end in 'ini'." if name[-3,3] != 'ini'
when 'subtribe'
raise NameError, "ICZN subtribe name does not end in 'ina'." if name[-3,3] != 'ina'
end
@name = name
end | [
"def",
"name",
"=",
"(",
"name",
")",
"case",
"@rank",
"when",
"'superfamily'",
"raise",
"NameError",
",",
"\"ICZN superfamily name does not end in 'oidae'.\"",
"if",
"name",
"[",
"-",
"5",
",",
"5",
"]",
"!=",
"'oidae'",
"when",
"'family'",
"raise",
"NameError",
",",
"\"ICZN family name does not end in 'idae'.\"",
"if",
"name",
"[",
"-",
"4",
",",
"4",
"]",
"!=",
"'idae'",
"when",
"'subfamily'",
"raise",
"NameError",
",",
"\"ICZN subfamily name does not end in 'inae'.\"",
"if",
"name",
"[",
"-",
"4",
",",
"4",
"]",
"!=",
"'inae'",
"when",
"'tribe'",
"raise",
"NameError",
",",
"\"ICZN tribe name does not end in 'ini'.\"",
"if",
"name",
"[",
"-",
"3",
",",
"3",
"]",
"!=",
"'ini'",
"when",
"'subtribe'",
"raise",
"NameError",
",",
"\"ICZN subtribe name does not end in 'ina'.\"",
"if",
"name",
"[",
"-",
"3",
",",
"3",
"]",
"!=",
"'ina'",
"end",
"@name",
"=",
"name",
"end"
] | Set the name, checks for family group restrictions. | [
"Set",
"the",
"name",
"checks",
"for",
"family",
"group",
"restrictions",
"."
] | 100dc94e7ffd378f6a81381c13768e35b2b65bf2 | https://github.com/SpeciesFileGroup/taxonifi/blob/100dc94e7ffd378f6a81381c13768e35b2b65bf2/lib/taxonifi/model/name.rb#L331-L345 | train |
ktonon/code_node | spec/fixtures/activerecord/src/active_record/transactions.rb | ActiveRecord.Transactions.rollback_active_record_state! | def rollback_active_record_state!
remember_transaction_record_state
yield
rescue Exception
IdentityMap.remove(self) if IdentityMap.enabled?
restore_transaction_record_state
raise
ensure
clear_transaction_record_state
end | ruby | def rollback_active_record_state!
remember_transaction_record_state
yield
rescue Exception
IdentityMap.remove(self) if IdentityMap.enabled?
restore_transaction_record_state
raise
ensure
clear_transaction_record_state
end | [
"def",
"rollback_active_record_state!",
"remember_transaction_record_state",
"yield",
"rescue",
"Exception",
"IdentityMap",
".",
"remove",
"(",
"self",
")",
"if",
"IdentityMap",
".",
"enabled?",
"restore_transaction_record_state",
"raise",
"ensure",
"clear_transaction_record_state",
"end"
] | Reset id and @new_record if the transaction rolls back. | [
"Reset",
"id",
"and"
] | 48d5d1a7442d9cade602be4fb782a1b56c7677f5 | https://github.com/ktonon/code_node/blob/48d5d1a7442d9cade602be4fb782a1b56c7677f5/spec/fixtures/activerecord/src/active_record/transactions.rb#L268-L277 | train |
ktonon/code_node | spec/fixtures/activerecord/src/active_record/transactions.rb | ActiveRecord.Transactions.rolledback! | def rolledback!(force_restore_state = false) #:nodoc:
run_callbacks :rollback
ensure
IdentityMap.remove(self) if IdentityMap.enabled?
restore_transaction_record_state(force_restore_state)
end | ruby | def rolledback!(force_restore_state = false) #:nodoc:
run_callbacks :rollback
ensure
IdentityMap.remove(self) if IdentityMap.enabled?
restore_transaction_record_state(force_restore_state)
end | [
"def",
"rolledback!",
"(",
"force_restore_state",
"=",
"false",
")",
"#:nodoc:",
"run_callbacks",
":rollback",
"ensure",
"IdentityMap",
".",
"remove",
"(",
"self",
")",
"if",
"IdentityMap",
".",
"enabled?",
"restore_transaction_record_state",
"(",
"force_restore_state",
")",
"end"
] | Call the after rollback callbacks. The restore_state argument indicates if the record
state should be rolled back to the beginning or just to the last savepoint. | [
"Call",
"the",
"after",
"rollback",
"callbacks",
".",
"The",
"restore_state",
"argument",
"indicates",
"if",
"the",
"record",
"state",
"should",
"be",
"rolled",
"back",
"to",
"the",
"beginning",
"or",
"just",
"to",
"the",
"last",
"savepoint",
"."
] | 48d5d1a7442d9cade602be4fb782a1b56c7677f5 | https://github.com/ktonon/code_node/blob/48d5d1a7442d9cade602be4fb782a1b56c7677f5/spec/fixtures/activerecord/src/active_record/transactions.rb#L288-L293 | train |
irvingwashington/gem_footprint_analyzer | lib/gem_footprint_analyzer/child_process.rb | GemFootprintAnalyzer.ChildProcess.start_child | def start_child
@child_thread ||= Thread.new do # rubocop:disable Naming/MemoizedInstanceVariableName
Open3.popen3(child_env_vars, *ruby_command, context_file) do |_, stdout, stderr|
@pid = stdout.gets.strip.to_i
while (line = stderr.gets)
print "!! #{line}"
end
end
end
end | ruby | def start_child
@child_thread ||= Thread.new do # rubocop:disable Naming/MemoizedInstanceVariableName
Open3.popen3(child_env_vars, *ruby_command, context_file) do |_, stdout, stderr|
@pid = stdout.gets.strip.to_i
while (line = stderr.gets)
print "!! #{line}"
end
end
end
end | [
"def",
"start_child",
"@child_thread",
"||=",
"Thread",
".",
"new",
"do",
"# rubocop:disable Naming/MemoizedInstanceVariableName",
"Open3",
".",
"popen3",
"(",
"child_env_vars",
",",
"ruby_command",
",",
"context_file",
")",
"do",
"|",
"_",
",",
"stdout",
",",
"stderr",
"|",
"@pid",
"=",
"stdout",
".",
"gets",
".",
"strip",
".",
"to_i",
"while",
"(",
"line",
"=",
"stderr",
".",
"gets",
")",
"print",
"\"!! #{line}\"",
"end",
"end",
"end",
"end"
] | Sets necessary ivars
Starts a child process in a child-watching-thread
Reads it's PID from the new process' STDOUT and sets it as an instance variable | [
"Sets",
"necessary",
"ivars",
"Starts",
"a",
"child",
"process",
"in",
"a",
"child",
"-",
"watching",
"-",
"thread",
"Reads",
"it",
"s",
"PID",
"from",
"the",
"new",
"process",
"STDOUT",
"and",
"sets",
"it",
"as",
"an",
"instance",
"variable"
] | 19a8892f6baaeb16b1b166144c4f73852396220c | https://github.com/irvingwashington/gem_footprint_analyzer/blob/19a8892f6baaeb16b1b166144c4f73852396220c/lib/gem_footprint_analyzer/child_process.rb#L21-L31 | train |
davidan1981/rails-identity | app/controllers/rails_identity/users_controller.rb | RailsIdentity.UsersController.create | def create
logger.debug("Create new user")
@user = User.new(user_params)
if @user.save
# Save succeeded. Render the response based on the created user.
render json: @user,
except: [:verification_token, :reset_token, :password_digest],
status: 201
# Then, issue the verification token and send the email for
# verification.
@user.issue_token(:verification_token)
@user.save
user_mailer.email_verification(@user).deliver_later
else
render_errors 400, @user.errors.full_messages
end
end | ruby | def create
logger.debug("Create new user")
@user = User.new(user_params)
if @user.save
# Save succeeded. Render the response based on the created user.
render json: @user,
except: [:verification_token, :reset_token, :password_digest],
status: 201
# Then, issue the verification token and send the email for
# verification.
@user.issue_token(:verification_token)
@user.save
user_mailer.email_verification(@user).deliver_later
else
render_errors 400, @user.errors.full_messages
end
end | [
"def",
"create",
"logger",
".",
"debug",
"(",
"\"Create new user\"",
")",
"@user",
"=",
"User",
".",
"new",
"(",
"user_params",
")",
"if",
"@user",
".",
"save",
"# Save succeeded. Render the response based on the created user.",
"render",
"json",
":",
"@user",
",",
"except",
":",
"[",
":verification_token",
",",
":reset_token",
",",
":password_digest",
"]",
",",
"status",
":",
"201",
"# Then, issue the verification token and send the email for",
"# verification.",
"@user",
".",
"issue_token",
"(",
":verification_token",
")",
"@user",
".",
"save",
"user_mailer",
".",
"email_verification",
"(",
"@user",
")",
".",
"deliver_later",
"else",
"render_errors",
"400",
",",
"@user",
".",
"errors",
".",
"full_messages",
"end",
"end"
] | Creates a new user. This action does not require any auth although it
is optional. | [
"Creates",
"a",
"new",
"user",
".",
"This",
"action",
"does",
"not",
"require",
"any",
"auth",
"although",
"it",
"is",
"optional",
"."
] | 12b0d6fd85bd9019d3be7f4fd79fbca39f824ca0 | https://github.com/davidan1981/rails-identity/blob/12b0d6fd85bd9019d3be7f4fd79fbca39f824ca0/app/controllers/rails_identity/users_controller.rb#L31-L49 | train |
davidan1981/rails-identity | app/controllers/rails_identity/users_controller.rb | RailsIdentity.UsersController.update_user | def update_user(update_user_params)
if @user.update_attributes(update_user_params)
render json: @user, except: [:password_digest]
else
render_errors 400, @user.errors.full_messages
end
end | ruby | def update_user(update_user_params)
if @user.update_attributes(update_user_params)
render json: @user, except: [:password_digest]
else
render_errors 400, @user.errors.full_messages
end
end | [
"def",
"update_user",
"(",
"update_user_params",
")",
"if",
"@user",
".",
"update_attributes",
"(",
"update_user_params",
")",
"render",
"json",
":",
"@user",
",",
"except",
":",
"[",
":password_digest",
"]",
"else",
"render_errors",
"400",
",",
"@user",
".",
"errors",
".",
"full_messages",
"end",
"end"
] | This method normally updates the user using permitted params. | [
"This",
"method",
"normally",
"updates",
"the",
"user",
"using",
"permitted",
"params",
"."
] | 12b0d6fd85bd9019d3be7f4fd79fbca39f824ca0 | https://github.com/davidan1981/rails-identity/blob/12b0d6fd85bd9019d3be7f4fd79fbca39f824ca0/app/controllers/rails_identity/users_controller.rb#L139-L145 | train |
davidan1981/rails-identity | app/controllers/rails_identity/users_controller.rb | RailsIdentity.UsersController.update_token | def update_token(kind)
@user.issue_token(kind)
@user.save
if kind == :reset_token
user_mailer.password_reset(@user).deliver_later
else
user_mailer.email_verification(@user).deliver_later
end
render body: '', status: 204
end | ruby | def update_token(kind)
@user.issue_token(kind)
@user.save
if kind == :reset_token
user_mailer.password_reset(@user).deliver_later
else
user_mailer.email_verification(@user).deliver_later
end
render body: '', status: 204
end | [
"def",
"update_token",
"(",
"kind",
")",
"@user",
".",
"issue_token",
"(",
"kind",
")",
"@user",
".",
"save",
"if",
"kind",
"==",
":reset_token",
"user_mailer",
".",
"password_reset",
"(",
"@user",
")",
".",
"deliver_later",
"else",
"user_mailer",
".",
"email_verification",
"(",
"@user",
")",
".",
"deliver_later",
"end",
"render",
"body",
":",
"''",
",",
"status",
":",
"204",
"end"
] | This method updates user with a new reset token. Only used for this
operation. | [
"This",
"method",
"updates",
"user",
"with",
"a",
"new",
"reset",
"token",
".",
"Only",
"used",
"for",
"this",
"operation",
"."
] | 12b0d6fd85bd9019d3be7f4fd79fbca39f824ca0 | https://github.com/davidan1981/rails-identity/blob/12b0d6fd85bd9019d3be7f4fd79fbca39f824ca0/app/controllers/rails_identity/users_controller.rb#L151-L160 | train |
PeterCamilleri/format_output | lib/format_output/builders/bullet_builder.rb | FormatOutput.BulletPointBuilder.add | def add(bullet, *items)
items.each do |item|
@bullet_data << [bullet.to_s, item]
bullet = ""
end
end | ruby | def add(bullet, *items)
items.each do |item|
@bullet_data << [bullet.to_s, item]
bullet = ""
end
end | [
"def",
"add",
"(",
"bullet",
",",
"*",
"items",
")",
"items",
".",
"each",
"do",
"|",
"item",
"|",
"@bullet_data",
"<<",
"[",
"bullet",
".",
"to_s",
",",
"item",
"]",
"bullet",
"=",
"\"\"",
"end",
"end"
] | Prepare a blank slate.
Add items to these bullet points. | [
"Prepare",
"a",
"blank",
"slate",
".",
"Add",
"items",
"to",
"these",
"bullet",
"points",
"."
] | 95dac24bd21f618a74bb665a44235491d725e1b7 | https://github.com/PeterCamilleri/format_output/blob/95dac24bd21f618a74bb665a44235491d725e1b7/lib/format_output/builders/bullet_builder.rb#L18-L23 | train |
PeterCamilleri/format_output | lib/format_output/builders/bullet_builder.rb | FormatOutput.BulletPointBuilder.render | def render
@key_length, results = get_key_length, []
@bullet_data.each do |key, item|
results.concat(render_bullet(key, item))
end
@bullet_data = []
results
end | ruby | def render
@key_length, results = get_key_length, []
@bullet_data.each do |key, item|
results.concat(render_bullet(key, item))
end
@bullet_data = []
results
end | [
"def",
"render",
"@key_length",
",",
"results",
"=",
"get_key_length",
",",
"[",
"]",
"@bullet_data",
".",
"each",
"do",
"|",
"key",
",",
"item",
"|",
"results",
".",
"concat",
"(",
"render_bullet",
"(",
"key",
",",
"item",
")",
")",
"end",
"@bullet_data",
"=",
"[",
"]",
"results",
"end"
] | Render the bullet points as an array of strings. | [
"Render",
"the",
"bullet",
"points",
"as",
"an",
"array",
"of",
"strings",
"."
] | 95dac24bd21f618a74bb665a44235491d725e1b7 | https://github.com/PeterCamilleri/format_output/blob/95dac24bd21f618a74bb665a44235491d725e1b7/lib/format_output/builders/bullet_builder.rb#L26-L35 | train |
thriventures/storage_room_gem | lib/storage_room/model.rb | StorageRoom.Model.create | def create
return false unless new_record?
run_callbacks :save do
run_callbacks :create do
httparty = self.class.post(self.class.index_path, request_options.merge(:body => to_json))
handle_save_response(httparty)
end
end
end | ruby | def create
return false unless new_record?
run_callbacks :save do
run_callbacks :create do
httparty = self.class.post(self.class.index_path, request_options.merge(:body => to_json))
handle_save_response(httparty)
end
end
end | [
"def",
"create",
"return",
"false",
"unless",
"new_record?",
"run_callbacks",
":save",
"do",
"run_callbacks",
":create",
"do",
"httparty",
"=",
"self",
".",
"class",
".",
"post",
"(",
"self",
".",
"class",
".",
"index_path",
",",
"request_options",
".",
"merge",
"(",
":body",
"=>",
"to_json",
")",
")",
"handle_save_response",
"(",
"httparty",
")",
"end",
"end",
"end"
] | Create a new model on the server | [
"Create",
"a",
"new",
"model",
"on",
"the",
"server"
] | cadf132b865ff82f7b09fadfec1d294a714c6728 | https://github.com/thriventures/storage_room_gem/blob/cadf132b865ff82f7b09fadfec1d294a714c6728/lib/storage_room/model.rb#L65-L73 | train |
thriventures/storage_room_gem | lib/storage_room/model.rb | StorageRoom.Model.update | def update
return false if new_record?
run_callbacks :save do
run_callbacks :update do
httparty = self.class.put(self[:@url], request_options.merge(:body => to_json))
handle_save_response(httparty)
end
end
end | ruby | def update
return false if new_record?
run_callbacks :save do
run_callbacks :update do
httparty = self.class.put(self[:@url], request_options.merge(:body => to_json))
handle_save_response(httparty)
end
end
end | [
"def",
"update",
"return",
"false",
"if",
"new_record?",
"run_callbacks",
":save",
"do",
"run_callbacks",
":update",
"do",
"httparty",
"=",
"self",
".",
"class",
".",
"put",
"(",
"self",
"[",
":@url",
"]",
",",
"request_options",
".",
"merge",
"(",
":body",
"=>",
"to_json",
")",
")",
"handle_save_response",
"(",
"httparty",
")",
"end",
"end",
"end"
] | Update an existing model on the server | [
"Update",
"an",
"existing",
"model",
"on",
"the",
"server"
] | cadf132b865ff82f7b09fadfec1d294a714c6728 | https://github.com/thriventures/storage_room_gem/blob/cadf132b865ff82f7b09fadfec1d294a714c6728/lib/storage_room/model.rb#L76-L84 | train |
thriventures/storage_room_gem | lib/storage_room/model.rb | StorageRoom.Model.destroy | def destroy
return false if new_record?
run_callbacks :destroy do
httparty = self.class.delete(self[:@url], request_options)
self.class.handle_critical_response_errors(httparty)
end
true
end | ruby | def destroy
return false if new_record?
run_callbacks :destroy do
httparty = self.class.delete(self[:@url], request_options)
self.class.handle_critical_response_errors(httparty)
end
true
end | [
"def",
"destroy",
"return",
"false",
"if",
"new_record?",
"run_callbacks",
":destroy",
"do",
"httparty",
"=",
"self",
".",
"class",
".",
"delete",
"(",
"self",
"[",
":@url",
"]",
",",
"request_options",
")",
"self",
".",
"class",
".",
"handle_critical_response_errors",
"(",
"httparty",
")",
"end",
"true",
"end"
] | Delete an existing model on the server | [
"Delete",
"an",
"existing",
"model",
"on",
"the",
"server"
] | cadf132b865ff82f7b09fadfec1d294a714c6728 | https://github.com/thriventures/storage_room_gem/blob/cadf132b865ff82f7b09fadfec1d294a714c6728/lib/storage_room/model.rb#L87-L96 | train |
thriventures/storage_room_gem | lib/storage_room/model.rb | StorageRoom.Model.to_hash | def to_hash(args = {}) # :nodoc:
args ||= {}
if args[:nested]
{'url' => self[:@url] || self[:url]}
else
hash = super
hash.merge!('@version' => self['@version']) unless new_record?
{self.class.json_name => hash}
end
end | ruby | def to_hash(args = {}) # :nodoc:
args ||= {}
if args[:nested]
{'url' => self[:@url] || self[:url]}
else
hash = super
hash.merge!('@version' => self['@version']) unless new_record?
{self.class.json_name => hash}
end
end | [
"def",
"to_hash",
"(",
"args",
"=",
"{",
"}",
")",
"# :nodoc:",
"args",
"||=",
"{",
"}",
"if",
"args",
"[",
":nested",
"]",
"{",
"'url'",
"=>",
"self",
"[",
":@url",
"]",
"||",
"self",
"[",
":url",
"]",
"}",
"else",
"hash",
"=",
"super",
"hash",
".",
"merge!",
"(",
"'@version'",
"=>",
"self",
"[",
"'@version'",
"]",
")",
"unless",
"new_record?",
"{",
"self",
".",
"class",
".",
"json_name",
"=>",
"hash",
"}",
"end",
"end"
] | ActiveSupport caused problems when using as_json, so using to_hash | [
"ActiveSupport",
"caused",
"problems",
"when",
"using",
"as_json",
"so",
"using",
"to_hash"
] | cadf132b865ff82f7b09fadfec1d294a714c6728 | https://github.com/thriventures/storage_room_gem/blob/cadf132b865ff82f7b09fadfec1d294a714c6728/lib/storage_room/model.rb#L104-L114 | train |
vojto/active_harmony | lib/active_harmony/service.rb | ActiveHarmony.Service.retrieve | def retrieve(url, method = :get, headers = {}, data = nil)
puts "[ActiveHarmony] Retrieving data:"
puts "[ActiveHarmony] URL: #{url}"
puts "[ActiveHarmony] Method: #{method}"
puts "[ActiveHarmony] Headers: #{headers.inspect}"
puts "[ActiveHarmony] Data: #{data.inspect}" if data
if defined?(Rails) && !Rails.env.test?
data = retrieve_with_typhoeus(url, method, headers, data)
else
data = retrieve_with_http(url, method, headers, data)
end
data
end | ruby | def retrieve(url, method = :get, headers = {}, data = nil)
puts "[ActiveHarmony] Retrieving data:"
puts "[ActiveHarmony] URL: #{url}"
puts "[ActiveHarmony] Method: #{method}"
puts "[ActiveHarmony] Headers: #{headers.inspect}"
puts "[ActiveHarmony] Data: #{data.inspect}" if data
if defined?(Rails) && !Rails.env.test?
data = retrieve_with_typhoeus(url, method, headers, data)
else
data = retrieve_with_http(url, method, headers, data)
end
data
end | [
"def",
"retrieve",
"(",
"url",
",",
"method",
"=",
":get",
",",
"headers",
"=",
"{",
"}",
",",
"data",
"=",
"nil",
")",
"puts",
"\"[ActiveHarmony] Retrieving data:\"",
"puts",
"\"[ActiveHarmony] URL: #{url}\"",
"puts",
"\"[ActiveHarmony] Method: #{method}\"",
"puts",
"\"[ActiveHarmony] Headers: #{headers.inspect}\"",
"puts",
"\"[ActiveHarmony] Data: #{data.inspect}\"",
"if",
"data",
"if",
"defined?",
"(",
"Rails",
")",
"&&",
"!",
"Rails",
".",
"env",
".",
"test?",
"data",
"=",
"retrieve_with_typhoeus",
"(",
"url",
",",
"method",
",",
"headers",
",",
"data",
")",
"else",
"data",
"=",
"retrieve_with_http",
"(",
"url",
",",
"method",
",",
"headers",
",",
"data",
")",
"end",
"data",
"end"
] | Retrieving data from networks
Retrieves data from URL
@param [String] URL
@return [String] Retrieved data from the URL | [
"Retrieving",
"data",
"from",
"networks"
] | 03e5c67ea7a1f986c729001c4fec944bf116640f | https://github.com/vojto/active_harmony/blob/03e5c67ea7a1f986c729001c4fec944bf116640f/lib/active_harmony/service.rb#L87-L99 | train |
vojto/active_harmony | lib/active_harmony/service.rb | ActiveHarmony.Service.list | def list(object_type)
url = generate_rest_url(:list, object_type)
result = retrieve(url.path)
parsed_result = parse_xml(result)
find_object_in_result(parsed_result, object_type, :list)
end | ruby | def list(object_type)
url = generate_rest_url(:list, object_type)
result = retrieve(url.path)
parsed_result = parse_xml(result)
find_object_in_result(parsed_result, object_type, :list)
end | [
"def",
"list",
"(",
"object_type",
")",
"url",
"=",
"generate_rest_url",
"(",
":list",
",",
"object_type",
")",
"result",
"=",
"retrieve",
"(",
"url",
".",
"path",
")",
"parsed_result",
"=",
"parse_xml",
"(",
"result",
")",
"find_object_in_result",
"(",
"parsed_result",
",",
"object_type",
",",
":list",
")",
"end"
] | Working with REST services
List collection of remote objects
@param [Symbol] Object type
@return [Array<Hash>] Array of objects | [
"Working",
"with",
"REST",
"services"
] | 03e5c67ea7a1f986c729001c4fec944bf116640f | https://github.com/vojto/active_harmony/blob/03e5c67ea7a1f986c729001c4fec944bf116640f/lib/active_harmony/service.rb#L166-L171 | train |
vojto/active_harmony | lib/active_harmony/service.rb | ActiveHarmony.Service.show | def show(object_type, id)
url = generate_rest_url(:show, object_type, id)
result = retrieve(url.path)
parsed_result = parse_xml(result)
find_object_in_result(parsed_result, object_type, :show)
end | ruby | def show(object_type, id)
url = generate_rest_url(:show, object_type, id)
result = retrieve(url.path)
parsed_result = parse_xml(result)
find_object_in_result(parsed_result, object_type, :show)
end | [
"def",
"show",
"(",
"object_type",
",",
"id",
")",
"url",
"=",
"generate_rest_url",
"(",
":show",
",",
"object_type",
",",
"id",
")",
"result",
"=",
"retrieve",
"(",
"url",
".",
"path",
")",
"parsed_result",
"=",
"parse_xml",
"(",
"result",
")",
"find_object_in_result",
"(",
"parsed_result",
",",
"object_type",
",",
":show",
")",
"end"
] | Shows remote object
@param [Symbol] Object type
@param [String] Object ID
@return [Hash] Object | [
"Shows",
"remote",
"object"
] | 03e5c67ea7a1f986c729001c4fec944bf116640f | https://github.com/vojto/active_harmony/blob/03e5c67ea7a1f986c729001c4fec944bf116640f/lib/active_harmony/service.rb#L178-L183 | train |
vojto/active_harmony | lib/active_harmony/service.rb | ActiveHarmony.Service.update | def update(object_type, id, data)
url = generate_rest_url(:update, object_type, id)
object_name = object_name_for(object_type, :update)
xml_data = data.to_xml(:root => object_name, :skip_instruct => true, :dasherize => false)
result = retrieve(url.path, url.method, {'Content-type' => 'application/xml'}, xml_data)
find_object_in_result(result, object_type, :update)
end | ruby | def update(object_type, id, data)
url = generate_rest_url(:update, object_type, id)
object_name = object_name_for(object_type, :update)
xml_data = data.to_xml(:root => object_name, :skip_instruct => true, :dasherize => false)
result = retrieve(url.path, url.method, {'Content-type' => 'application/xml'}, xml_data)
find_object_in_result(result, object_type, :update)
end | [
"def",
"update",
"(",
"object_type",
",",
"id",
",",
"data",
")",
"url",
"=",
"generate_rest_url",
"(",
":update",
",",
"object_type",
",",
"id",
")",
"object_name",
"=",
"object_name_for",
"(",
"object_type",
",",
":update",
")",
"xml_data",
"=",
"data",
".",
"to_xml",
"(",
":root",
"=>",
"object_name",
",",
":skip_instruct",
"=>",
"true",
",",
":dasherize",
"=>",
"false",
")",
"result",
"=",
"retrieve",
"(",
"url",
".",
"path",
",",
"url",
".",
"method",
",",
"{",
"'Content-type'",
"=>",
"'application/xml'",
"}",
",",
"xml_data",
")",
"find_object_in_result",
"(",
"result",
",",
"object_type",
",",
":update",
")",
"end"
] | Updates remote object
@param [Symbol] Object type
@param [String] Object ID
@param [Hash] Data to be sent | [
"Updates",
"remote",
"object"
] | 03e5c67ea7a1f986c729001c4fec944bf116640f | https://github.com/vojto/active_harmony/blob/03e5c67ea7a1f986c729001c4fec944bf116640f/lib/active_harmony/service.rb#L190-L196 | train |
vojto/active_harmony | lib/active_harmony/service.rb | ActiveHarmony.Service.create | def create(object_type, data)
url = generate_rest_url(:create, object_type)
object_name = object_name_for(object_type, :create)
xml_data = data.to_xml(:root => object_name, :skip_instruct => true, :dasherize => false)
result = retrieve(url.path, url.method, {'Content-type' => 'application/xml'}, xml_data)
parsed_result = parse_xml(result)
find_object_in_result(parsed_result, object_type, :create)
end | ruby | def create(object_type, data)
url = generate_rest_url(:create, object_type)
object_name = object_name_for(object_type, :create)
xml_data = data.to_xml(:root => object_name, :skip_instruct => true, :dasherize => false)
result = retrieve(url.path, url.method, {'Content-type' => 'application/xml'}, xml_data)
parsed_result = parse_xml(result)
find_object_in_result(parsed_result, object_type, :create)
end | [
"def",
"create",
"(",
"object_type",
",",
"data",
")",
"url",
"=",
"generate_rest_url",
"(",
":create",
",",
"object_type",
")",
"object_name",
"=",
"object_name_for",
"(",
"object_type",
",",
":create",
")",
"xml_data",
"=",
"data",
".",
"to_xml",
"(",
":root",
"=>",
"object_name",
",",
":skip_instruct",
"=>",
"true",
",",
":dasherize",
"=>",
"false",
")",
"result",
"=",
"retrieve",
"(",
"url",
".",
"path",
",",
"url",
".",
"method",
",",
"{",
"'Content-type'",
"=>",
"'application/xml'",
"}",
",",
"xml_data",
")",
"parsed_result",
"=",
"parse_xml",
"(",
"result",
")",
"find_object_in_result",
"(",
"parsed_result",
",",
"object_type",
",",
":create",
")",
"end"
] | Creates a new remote object
@param [Symbol] Object type
@param [Hash] Data to be sent | [
"Creates",
"a",
"new",
"remote",
"object"
] | 03e5c67ea7a1f986c729001c4fec944bf116640f | https://github.com/vojto/active_harmony/blob/03e5c67ea7a1f986c729001c4fec944bf116640f/lib/active_harmony/service.rb#L202-L209 | train |
vojto/active_harmony | lib/active_harmony/service.rb | ActiveHarmony.Service.custom_url_for | def custom_url_for(object_type, action)
path = @paths.find do |path|
path[:object_type] == object_type &&
path[:action] == action
end
if path
ServiceUrl.new(generate_url(path[:path]), path[:method])
end
end | ruby | def custom_url_for(object_type, action)
path = @paths.find do |path|
path[:object_type] == object_type &&
path[:action] == action
end
if path
ServiceUrl.new(generate_url(path[:path]), path[:method])
end
end | [
"def",
"custom_url_for",
"(",
"object_type",
",",
"action",
")",
"path",
"=",
"@paths",
".",
"find",
"do",
"|",
"path",
"|",
"path",
"[",
":object_type",
"]",
"==",
"object_type",
"&&",
"path",
"[",
":action",
"]",
"==",
"action",
"end",
"if",
"path",
"ServiceUrl",
".",
"new",
"(",
"generate_url",
"(",
"path",
"[",
":path",
"]",
")",
",",
"path",
"[",
":method",
"]",
")",
"end",
"end"
] | Returns custom path
@param [Symbol] Object type
@param [Symbol] Action
@return [Service::ServiceUrl] Custom path | [
"Returns",
"custom",
"path"
] | 03e5c67ea7a1f986c729001c4fec944bf116640f | https://github.com/vojto/active_harmony/blob/03e5c67ea7a1f986c729001c4fec944bf116640f/lib/active_harmony/service.rb#L251-L259 | train |
vojto/active_harmony | lib/active_harmony/service.rb | ActiveHarmony.Service.object_name_for | def object_name_for(object_type, action)
object_name = @object_names.find do |object_name|
object_name[:object_type] == object_type
object_name[:action] == action
end
object_name = object_name ? object_name[:new_object_name] : nil
unless object_name
object_name = object_type.to_s.gsub('-', '_')
end
object_name
end | ruby | def object_name_for(object_type, action)
object_name = @object_names.find do |object_name|
object_name[:object_type] == object_type
object_name[:action] == action
end
object_name = object_name ? object_name[:new_object_name] : nil
unless object_name
object_name = object_type.to_s.gsub('-', '_')
end
object_name
end | [
"def",
"object_name_for",
"(",
"object_type",
",",
"action",
")",
"object_name",
"=",
"@object_names",
".",
"find",
"do",
"|",
"object_name",
"|",
"object_name",
"[",
":object_type",
"]",
"==",
"object_type",
"object_name",
"[",
":action",
"]",
"==",
"action",
"end",
"object_name",
"=",
"object_name",
"?",
"object_name",
"[",
":new_object_name",
"]",
":",
"nil",
"unless",
"object_name",
"object_name",
"=",
"object_type",
".",
"to_s",
".",
"gsub",
"(",
"'-'",
",",
"'_'",
")",
"end",
"object_name",
"end"
] | Returns custom object name for action
@param [Symbol] Object type
@param [Symbol] Action | [
"Returns",
"custom",
"object",
"name",
"for",
"action"
] | 03e5c67ea7a1f986c729001c4fec944bf116640f | https://github.com/vojto/active_harmony/blob/03e5c67ea7a1f986c729001c4fec944bf116640f/lib/active_harmony/service.rb#L281-L291 | train |
Illianthe/lolbase | lib/lolbase/connection.rb | LoLBase.Connection.get | def get(path, options = {})
if options[:query].nil?
options.merge!({ query: { api_key: @key } })
else
options[:query].merge!({ api_key: @key })
end
response = self.class.get path, options
raise LoLBaseError, response.message if response.code != 200
response.body
end | ruby | def get(path, options = {})
if options[:query].nil?
options.merge!({ query: { api_key: @key } })
else
options[:query].merge!({ api_key: @key })
end
response = self.class.get path, options
raise LoLBaseError, response.message if response.code != 200
response.body
end | [
"def",
"get",
"(",
"path",
",",
"options",
"=",
"{",
"}",
")",
"if",
"options",
"[",
":query",
"]",
".",
"nil?",
"options",
".",
"merge!",
"(",
"{",
"query",
":",
"{",
"api_key",
":",
"@key",
"}",
"}",
")",
"else",
"options",
"[",
":query",
"]",
".",
"merge!",
"(",
"{",
"api_key",
":",
"@key",
"}",
")",
"end",
"response",
"=",
"self",
".",
"class",
".",
"get",
"path",
",",
"options",
"raise",
"LoLBaseError",
",",
"response",
".",
"message",
"if",
"response",
".",
"code",
"!=",
"200",
"response",
".",
"body",
"end"
] | Override HTTParty's get method to append the API key and to process errors returned from request | [
"Override",
"HTTParty",
"s",
"get",
"method",
"to",
"append",
"the",
"API",
"key",
"and",
"to",
"process",
"errors",
"returned",
"from",
"request"
] | b622315bb3e9e44a0e33da2d34a89e524fd8863e | https://github.com/Illianthe/lolbase/blob/b622315bb3e9e44a0e33da2d34a89e524fd8863e/lib/lolbase/connection.rb#L13-L23 | train |
baroquebobcat/sinatra-twitter-oauth | lib/sinatra-twitter-oauth/helpers.rb | Sinatra::TwitterOAuth.Helpers.login_required | def login_required
setup_client
@user = ::TwitterOAuth::User.new(@client, session[:user]) if session[:user]
@rate_limit_status = @client.rate_limit_status
redirect '/login' unless user
end | ruby | def login_required
setup_client
@user = ::TwitterOAuth::User.new(@client, session[:user]) if session[:user]
@rate_limit_status = @client.rate_limit_status
redirect '/login' unless user
end | [
"def",
"login_required",
"setup_client",
"@user",
"=",
"::",
"TwitterOAuth",
"::",
"User",
".",
"new",
"(",
"@client",
",",
"session",
"[",
":user",
"]",
")",
"if",
"session",
"[",
":user",
"]",
"@rate_limit_status",
"=",
"@client",
".",
"rate_limit_status",
"redirect",
"'/login'",
"unless",
"user",
"end"
] | Redirects to login unless there is an authenticated user | [
"Redirects",
"to",
"login",
"unless",
"there",
"is",
"an",
"authenticated",
"user"
] | 8e11cc2a223a45b7c09152a492c48387f86cca2f | https://github.com/baroquebobcat/sinatra-twitter-oauth/blob/8e11cc2a223a45b7c09152a492c48387f86cca2f/lib/sinatra-twitter-oauth/helpers.rb#L12-L20 | train |
baroquebobcat/sinatra-twitter-oauth | lib/sinatra-twitter-oauth/helpers.rb | Sinatra::TwitterOAuth.Helpers.redirect_to_twitter_auth_url | def redirect_to_twitter_auth_url
request_token = get_request_token
session[:request_token] = request_token.token
session[:request_token_secret]= request_token.secret
redirect request_token.authorize_url.gsub('authorize','authenticate')
end | ruby | def redirect_to_twitter_auth_url
request_token = get_request_token
session[:request_token] = request_token.token
session[:request_token_secret]= request_token.secret
redirect request_token.authorize_url.gsub('authorize','authenticate')
end | [
"def",
"redirect_to_twitter_auth_url",
"request_token",
"=",
"get_request_token",
"session",
"[",
":request_token",
"]",
"=",
"request_token",
".",
"token",
"session",
"[",
":request_token_secret",
"]",
"=",
"request_token",
".",
"secret",
"redirect",
"request_token",
".",
"authorize_url",
".",
"gsub",
"(",
"'authorize'",
",",
"'authenticate'",
")",
"end"
] | gets the request token and redirects to twitter's OAuth endpoint | [
"gets",
"the",
"request",
"token",
"and",
"redirects",
"to",
"twitter",
"s",
"OAuth",
"endpoint"
] | 8e11cc2a223a45b7c09152a492c48387f86cca2f | https://github.com/baroquebobcat/sinatra-twitter-oauth/blob/8e11cc2a223a45b7c09152a492c48387f86cca2f/lib/sinatra-twitter-oauth/helpers.rb#L57-L64 | train |
gnomex/ruby-si-units | lib/si_units/unit.rb | SIUnits.Unit.convert_to | def convert_to(other)
return self if other.nil?
case other
when Unit
return self if other == self
target = other
when String
target = SIUnits::Unit.new(other.to_f)
else
raise ArgumentError, "Unknown target units"
end
end | ruby | def convert_to(other)
return self if other.nil?
case other
when Unit
return self if other == self
target = other
when String
target = SIUnits::Unit.new(other.to_f)
else
raise ArgumentError, "Unknown target units"
end
end | [
"def",
"convert_to",
"(",
"other",
")",
"return",
"self",
"if",
"other",
".",
"nil?",
"case",
"other",
"when",
"Unit",
"return",
"self",
"if",
"other",
"==",
"self",
"target",
"=",
"other",
"when",
"String",
"target",
"=",
"SIUnits",
"::",
"Unit",
".",
"new",
"(",
"other",
".",
"to_f",
")",
"else",
"raise",
"ArgumentError",
",",
"\"Unknown target units\"",
"end",
"end"
] | Comparable units
=> Compare with scale of kinds
convert to a specified unit string or to the same unit as another Unit | [
"Comparable",
"units",
"=",
">",
"Compare",
"with",
"scale",
"of",
"kinds",
"convert",
"to",
"a",
"specified",
"unit",
"string",
"or",
"to",
"the",
"same",
"unit",
"as",
"another",
"Unit"
] | 4a0a9f8c53c8d70372b4e0b82b8618a7e4a65245 | https://github.com/gnomex/ruby-si-units/blob/4a0a9f8c53c8d70372b4e0b82b8618a7e4a65245/lib/si_units/unit.rb#L95-L107 | train |
SteveOscar/fotofetch | lib/fotofetch.rb | Fotofetch.Fetch.add_sources | def add_sources(urls)
urls.each_with_object( {}.compare_by_identity ) do |link, pairs|
pairs[root_url(link)] = link
end
end | ruby | def add_sources(urls)
urls.each_with_object( {}.compare_by_identity ) do |link, pairs|
pairs[root_url(link)] = link
end
end | [
"def",
"add_sources",
"(",
"urls",
")",
"urls",
".",
"each_with_object",
"(",
"{",
"}",
".",
"compare_by_identity",
")",
"do",
"|",
"link",
",",
"pairs",
"|",
"pairs",
"[",
"root_url",
"(",
"link",
")",
"]",
"=",
"link",
"end",
"end"
] | Adds root urls as hash keys | [
"Adds",
"root",
"urls",
"as",
"hash",
"keys"
] | e6f7981bd69b61895b39c2a9874bca19488a8c08 | https://github.com/SteveOscar/fotofetch/blob/e6f7981bd69b61895b39c2a9874bca19488a8c08/lib/fotofetch.rb#L89-L93 | train |
SteveOscar/fotofetch | lib/fotofetch.rb | Fotofetch.Fetch.save_images | def save_images(urls, file_path)
urls.each_with_index do |url, i|
open("#{@topic.gsub(' ', '-')}_#{i}.jpg", 'wb') do |file|
file << open(url).read
end
end
end | ruby | def save_images(urls, file_path)
urls.each_with_index do |url, i|
open("#{@topic.gsub(' ', '-')}_#{i}.jpg", 'wb') do |file|
file << open(url).read
end
end
end | [
"def",
"save_images",
"(",
"urls",
",",
"file_path",
")",
"urls",
".",
"each_with_index",
"do",
"|",
"url",
",",
"i",
"|",
"open",
"(",
"\"#{@topic.gsub(' ', '-')}_#{i}.jpg\"",
",",
"'wb'",
")",
"do",
"|",
"file",
"|",
"file",
"<<",
"open",
"(",
"url",
")",
".",
"read",
"end",
"end",
"end"
] | takes an array of links | [
"takes",
"an",
"array",
"of",
"links"
] | e6f7981bd69b61895b39c2a9874bca19488a8c08 | https://github.com/SteveOscar/fotofetch/blob/e6f7981bd69b61895b39c2a9874bca19488a8c08/lib/fotofetch.rb#L96-L102 | train |
jeanlazarou/calco | lib/calco/sheet.rb | Calco.Sheet.row | def row row_number
if row_number == 0
cells = []
if @has_titles
@column_titles.each do |title|
cells << title ? title : ''
end
end
cells
else
@engine.generate(row_number, @columns, @cell_styles, @column_styles, @column_types)
end
end | ruby | def row row_number
if row_number == 0
cells = []
if @has_titles
@column_titles.each do |title|
cells << title ? title : ''
end
end
cells
else
@engine.generate(row_number, @columns, @cell_styles, @column_styles, @column_types)
end
end | [
"def",
"row",
"row_number",
"if",
"row_number",
"==",
"0",
"cells",
"=",
"[",
"]",
"if",
"@has_titles",
"@column_titles",
".",
"each",
"do",
"|",
"title",
"|",
"cells",
"<<",
"title",
"?",
"title",
":",
"''",
"end",
"end",
"cells",
"else",
"@engine",
".",
"generate",
"(",
"row_number",
",",
"@columns",
",",
"@cell_styles",
",",
"@column_styles",
",",
"@column_types",
")",
"end",
"end"
] | Returns an array of String objects generates by the engine
attached to this Sheet's Spreadsheet. | [
"Returns",
"an",
"array",
"of",
"String",
"objects",
"generates",
"by",
"the",
"engine",
"attached",
"to",
"this",
"Sheet",
"s",
"Spreadsheet",
"."
] | e70516e6b6eedd29b5e2924a7780157f2c1fff3b | https://github.com/jeanlazarou/calco/blob/e70516e6b6eedd29b5e2924a7780157f2c1fff3b/lib/calco/sheet.rb#L234-L256 | train |
jeanlazarou/calco | lib/calco/sheet.rb | Calco.Sheet.each_cell_definition | def each_cell_definition &block
if block.arity == 1
@columns.each do |column|
yield column
end
else
@columns.each_with_index do |column, i|
yield column, i
end
end
end | ruby | def each_cell_definition &block
if block.arity == 1
@columns.each do |column|
yield column
end
else
@columns.each_with_index do |column, i|
yield column, i
end
end
end | [
"def",
"each_cell_definition",
"&",
"block",
"if",
"block",
".",
"arity",
"==",
"1",
"@columns",
".",
"each",
"do",
"|",
"column",
"|",
"yield",
"column",
"end",
"else",
"@columns",
".",
"each_with_index",
"do",
"|",
"column",
",",
"i",
"|",
"yield",
"column",
",",
"i",
"end",
"end",
"end"
] | Calls the passed block for every Element, the cell definition,
attached to columns for this Sheet.
Depending an the block's arity, passes the Element or the Element
and the index to the given block.
Examples:
each_cell_definition {|column_def| ... }
each_cell_definition {|column_def, index| ... } | [
"Calls",
"the",
"passed",
"block",
"for",
"every",
"Element",
"the",
"cell",
"definition",
"attached",
"to",
"columns",
"for",
"this",
"Sheet",
"."
] | e70516e6b6eedd29b5e2924a7780157f2c1fff3b | https://github.com/jeanlazarou/calco/blob/e70516e6b6eedd29b5e2924a7780157f2c1fff3b/lib/calco/sheet.rb#L272-L288 | train |
nilsding/Empyrean | lib/empyrean/templaterenderer.rb | Empyrean.TemplateRenderer.render | def render
mentions = mentions_erb
hashtags = hashtags_erb
smileys = smileys_erb
clients = clients_erb
counters = {
tweets: @parsed[:tweet_count],
retweets: @parsed[:retweet_count],
retweets_percentage: (@parsed[:retweet_count] * 100 / @parsed[:tweet_count].to_f).round(2),
selftweets: @parsed[:selftweet_count],
selftweets_percentage: (@parsed[:selftweet_count] * 100 / @parsed[:tweet_count].to_f).round(2)
}
times_of_day = times_erb
erb = ERB.new @template
erb.result binding
end | ruby | def render
mentions = mentions_erb
hashtags = hashtags_erb
smileys = smileys_erb
clients = clients_erb
counters = {
tweets: @parsed[:tweet_count],
retweets: @parsed[:retweet_count],
retweets_percentage: (@parsed[:retweet_count] * 100 / @parsed[:tweet_count].to_f).round(2),
selftweets: @parsed[:selftweet_count],
selftweets_percentage: (@parsed[:selftweet_count] * 100 / @parsed[:tweet_count].to_f).round(2)
}
times_of_day = times_erb
erb = ERB.new @template
erb.result binding
end | [
"def",
"render",
"mentions",
"=",
"mentions_erb",
"hashtags",
"=",
"hashtags_erb",
"smileys",
"=",
"smileys_erb",
"clients",
"=",
"clients_erb",
"counters",
"=",
"{",
"tweets",
":",
"@parsed",
"[",
":tweet_count",
"]",
",",
"retweets",
":",
"@parsed",
"[",
":retweet_count",
"]",
",",
"retweets_percentage",
":",
"(",
"@parsed",
"[",
":retweet_count",
"]",
"*",
"100",
"/",
"@parsed",
"[",
":tweet_count",
"]",
".",
"to_f",
")",
".",
"round",
"(",
"2",
")",
",",
"selftweets",
":",
"@parsed",
"[",
":selftweet_count",
"]",
",",
"selftweets_percentage",
":",
"(",
"@parsed",
"[",
":selftweet_count",
"]",
"*",
"100",
"/",
"@parsed",
"[",
":tweet_count",
"]",
".",
"to_f",
")",
".",
"round",
"(",
"2",
")",
"}",
"times_of_day",
"=",
"times_erb",
"erb",
"=",
"ERB",
".",
"new",
"@template",
"erb",
".",
"result",
"binding",
"end"
] | Initializes a new TemplateRenderer.
template: The template to use (i.e. not the file name)
parsed_tweets: The dict that gets returned by TweetParser::merge_parsed
Renders @template. | [
"Initializes",
"a",
"new",
"TemplateRenderer",
"."
] | e652fb8966dfcd32968789af75e8d5a4f63134ec | https://github.com/nilsding/Empyrean/blob/e652fb8966dfcd32968789af75e8d5a4f63134ec/lib/empyrean/templaterenderer.rb#L38-L53 | train |
nilsding/Empyrean | lib/empyrean/templaterenderer.rb | Empyrean.TemplateRenderer.mentions_erb | def mentions_erb
retdict = {
enabled: @config[:mentions][:enabled],
top: [],
nottop: []
}
if @config[:mentions][:enabled]
top = @parsed[:mentions].slice(0, @config[:mentions][:top]) # top X mentions
top.each do |mention|
retdict[:top] << mention[1]
end
nottop = @parsed[:mentions].slice(@config[:mentions][:top], @config[:mentions][:notop]) # not in the top X
unless nottop.nil?
nottop.each do |mention|
mention[1].delete(:example)
retdict[:nottop] << mention[1]
end
end
end
retdict
end | ruby | def mentions_erb
retdict = {
enabled: @config[:mentions][:enabled],
top: [],
nottop: []
}
if @config[:mentions][:enabled]
top = @parsed[:mentions].slice(0, @config[:mentions][:top]) # top X mentions
top.each do |mention|
retdict[:top] << mention[1]
end
nottop = @parsed[:mentions].slice(@config[:mentions][:top], @config[:mentions][:notop]) # not in the top X
unless nottop.nil?
nottop.each do |mention|
mention[1].delete(:example)
retdict[:nottop] << mention[1]
end
end
end
retdict
end | [
"def",
"mentions_erb",
"retdict",
"=",
"{",
"enabled",
":",
"@config",
"[",
":mentions",
"]",
"[",
":enabled",
"]",
",",
"top",
":",
"[",
"]",
",",
"nottop",
":",
"[",
"]",
"}",
"if",
"@config",
"[",
":mentions",
"]",
"[",
":enabled",
"]",
"top",
"=",
"@parsed",
"[",
":mentions",
"]",
".",
"slice",
"(",
"0",
",",
"@config",
"[",
":mentions",
"]",
"[",
":top",
"]",
")",
"# top X mentions",
"top",
".",
"each",
"do",
"|",
"mention",
"|",
"retdict",
"[",
":top",
"]",
"<<",
"mention",
"[",
"1",
"]",
"end",
"nottop",
"=",
"@parsed",
"[",
":mentions",
"]",
".",
"slice",
"(",
"@config",
"[",
":mentions",
"]",
"[",
":top",
"]",
",",
"@config",
"[",
":mentions",
"]",
"[",
":notop",
"]",
")",
"# not in the top X",
"unless",
"nottop",
".",
"nil?",
"nottop",
".",
"each",
"do",
"|",
"mention",
"|",
"mention",
"[",
"1",
"]",
".",
"delete",
"(",
":example",
")",
"retdict",
"[",
":nottop",
"]",
"<<",
"mention",
"[",
"1",
"]",
"end",
"end",
"end",
"retdict",
"end"
] | Returns an array with the mentions which can be easily used within ERB. | [
"Returns",
"an",
"array",
"with",
"the",
"mentions",
"which",
"can",
"be",
"easily",
"used",
"within",
"ERB",
"."
] | e652fb8966dfcd32968789af75e8d5a4f63134ec | https://github.com/nilsding/Empyrean/blob/e652fb8966dfcd32968789af75e8d5a4f63134ec/lib/empyrean/templaterenderer.rb#L58-L81 | train |
nilsding/Empyrean | lib/empyrean/templaterenderer.rb | Empyrean.TemplateRenderer.hashtags_erb | def hashtags_erb
retdict = {
enabled: @config[:hashtags][:enabled],
top: [],
nottop: []
}
if @config[:hashtags][:enabled]
top = @parsed[:hashtags].slice(0, @config[:hashtags][:top]) # top X hashtags
top.each do |hashtag|
retdict[:top] << hashtag[1]
end
nottop = @parsed[:hashtags].slice(@config[:hashtags][:top], @config[:hashtags][:notop]) # not in the top X
unless nottop.nil?
nottop.each do |hashtag|
hashtag[1].delete(:example)
retdict[:nottop] << hashtag[1]
end
end
end
retdict
end | ruby | def hashtags_erb
retdict = {
enabled: @config[:hashtags][:enabled],
top: [],
nottop: []
}
if @config[:hashtags][:enabled]
top = @parsed[:hashtags].slice(0, @config[:hashtags][:top]) # top X hashtags
top.each do |hashtag|
retdict[:top] << hashtag[1]
end
nottop = @parsed[:hashtags].slice(@config[:hashtags][:top], @config[:hashtags][:notop]) # not in the top X
unless nottop.nil?
nottop.each do |hashtag|
hashtag[1].delete(:example)
retdict[:nottop] << hashtag[1]
end
end
end
retdict
end | [
"def",
"hashtags_erb",
"retdict",
"=",
"{",
"enabled",
":",
"@config",
"[",
":hashtags",
"]",
"[",
":enabled",
"]",
",",
"top",
":",
"[",
"]",
",",
"nottop",
":",
"[",
"]",
"}",
"if",
"@config",
"[",
":hashtags",
"]",
"[",
":enabled",
"]",
"top",
"=",
"@parsed",
"[",
":hashtags",
"]",
".",
"slice",
"(",
"0",
",",
"@config",
"[",
":hashtags",
"]",
"[",
":top",
"]",
")",
"# top X hashtags",
"top",
".",
"each",
"do",
"|",
"hashtag",
"|",
"retdict",
"[",
":top",
"]",
"<<",
"hashtag",
"[",
"1",
"]",
"end",
"nottop",
"=",
"@parsed",
"[",
":hashtags",
"]",
".",
"slice",
"(",
"@config",
"[",
":hashtags",
"]",
"[",
":top",
"]",
",",
"@config",
"[",
":hashtags",
"]",
"[",
":notop",
"]",
")",
"# not in the top X",
"unless",
"nottop",
".",
"nil?",
"nottop",
".",
"each",
"do",
"|",
"hashtag",
"|",
"hashtag",
"[",
"1",
"]",
".",
"delete",
"(",
":example",
")",
"retdict",
"[",
":nottop",
"]",
"<<",
"hashtag",
"[",
"1",
"]",
"end",
"end",
"end",
"retdict",
"end"
] | Returns an array with the hashtags which can be easily used within ERB. | [
"Returns",
"an",
"array",
"with",
"the",
"hashtags",
"which",
"can",
"be",
"easily",
"used",
"within",
"ERB",
"."
] | e652fb8966dfcd32968789af75e8d5a4f63134ec | https://github.com/nilsding/Empyrean/blob/e652fb8966dfcd32968789af75e8d5a4f63134ec/lib/empyrean/templaterenderer.rb#L85-L108 | train |
nilsding/Empyrean | lib/empyrean/templaterenderer.rb | Empyrean.TemplateRenderer.smileys_erb | def smileys_erb
retdict = {
enabled: @config[:smileys][:enabled],
top: [],
nottop: []
}
if @config[:smileys][:enabled]
top = @parsed[:smileys].slice(0, @config[:smileys][:top]) # top X smileys
top.each do |smiley|
retdict[:top] << smiley[1]
end
nottop = @parsed[:smileys].slice(@config[:smileys][:top], @config[:smileys][:notop]) # not in the top X
unless nottop.nil?
nottop.each do |smiley|
smiley[1].delete(:example)
retdict[:nottop] << smiley[1]
end
end
end
retdict
end | ruby | def smileys_erb
retdict = {
enabled: @config[:smileys][:enabled],
top: [],
nottop: []
}
if @config[:smileys][:enabled]
top = @parsed[:smileys].slice(0, @config[:smileys][:top]) # top X smileys
top.each do |smiley|
retdict[:top] << smiley[1]
end
nottop = @parsed[:smileys].slice(@config[:smileys][:top], @config[:smileys][:notop]) # not in the top X
unless nottop.nil?
nottop.each do |smiley|
smiley[1].delete(:example)
retdict[:nottop] << smiley[1]
end
end
end
retdict
end | [
"def",
"smileys_erb",
"retdict",
"=",
"{",
"enabled",
":",
"@config",
"[",
":smileys",
"]",
"[",
":enabled",
"]",
",",
"top",
":",
"[",
"]",
",",
"nottop",
":",
"[",
"]",
"}",
"if",
"@config",
"[",
":smileys",
"]",
"[",
":enabled",
"]",
"top",
"=",
"@parsed",
"[",
":smileys",
"]",
".",
"slice",
"(",
"0",
",",
"@config",
"[",
":smileys",
"]",
"[",
":top",
"]",
")",
"# top X smileys",
"top",
".",
"each",
"do",
"|",
"smiley",
"|",
"retdict",
"[",
":top",
"]",
"<<",
"smiley",
"[",
"1",
"]",
"end",
"nottop",
"=",
"@parsed",
"[",
":smileys",
"]",
".",
"slice",
"(",
"@config",
"[",
":smileys",
"]",
"[",
":top",
"]",
",",
"@config",
"[",
":smileys",
"]",
"[",
":notop",
"]",
")",
"# not in the top X",
"unless",
"nottop",
".",
"nil?",
"nottop",
".",
"each",
"do",
"|",
"smiley",
"|",
"smiley",
"[",
"1",
"]",
".",
"delete",
"(",
":example",
")",
"retdict",
"[",
":nottop",
"]",
"<<",
"smiley",
"[",
"1",
"]",
"end",
"end",
"end",
"retdict",
"end"
] | Returns an array with the smileys which can be easily used within ERB. | [
"Returns",
"an",
"array",
"with",
"the",
"smileys",
"which",
"can",
"be",
"easily",
"used",
"within",
"ERB",
"."
] | e652fb8966dfcd32968789af75e8d5a4f63134ec | https://github.com/nilsding/Empyrean/blob/e652fb8966dfcd32968789af75e8d5a4f63134ec/lib/empyrean/templaterenderer.rb#L112-L135 | train |
nilsding/Empyrean | lib/empyrean/templaterenderer.rb | Empyrean.TemplateRenderer.clients_erb | def clients_erb
retdict = {
enabled: @config[:clients][:enabled],
top: [],
nottop: []
}
if @config[:clients][:enabled]
top = @parsed[:clients].slice(0, @config[:clients][:top]) # top X clients
top.each do |client|
retdict[:top] << {
name: client[1][:name],
url: client[1][:url],
count: client[1][:count],
percentage: (client[1][:count] * 100 / @parsed[:tweet_count].to_f).round(2)
}
end
nottop = @parsed[:clients].slice(@config[:clients][:top], @config[:clients][:notop]) # not in the top X
unless nottop.nil?
nottop.each do |client|
client[1].delete(:example)
retdict[:nottop] << {
name: client[1][:name],
url: client[1][:url],
count: client[1][:count],
percentage: (client[1][:count] * 100 / @parsed[:tweet_count].to_f).round(2)
}
end
end
end
retdict
end | ruby | def clients_erb
retdict = {
enabled: @config[:clients][:enabled],
top: [],
nottop: []
}
if @config[:clients][:enabled]
top = @parsed[:clients].slice(0, @config[:clients][:top]) # top X clients
top.each do |client|
retdict[:top] << {
name: client[1][:name],
url: client[1][:url],
count: client[1][:count],
percentage: (client[1][:count] * 100 / @parsed[:tweet_count].to_f).round(2)
}
end
nottop = @parsed[:clients].slice(@config[:clients][:top], @config[:clients][:notop]) # not in the top X
unless nottop.nil?
nottop.each do |client|
client[1].delete(:example)
retdict[:nottop] << {
name: client[1][:name],
url: client[1][:url],
count: client[1][:count],
percentage: (client[1][:count] * 100 / @parsed[:tweet_count].to_f).round(2)
}
end
end
end
retdict
end | [
"def",
"clients_erb",
"retdict",
"=",
"{",
"enabled",
":",
"@config",
"[",
":clients",
"]",
"[",
":enabled",
"]",
",",
"top",
":",
"[",
"]",
",",
"nottop",
":",
"[",
"]",
"}",
"if",
"@config",
"[",
":clients",
"]",
"[",
":enabled",
"]",
"top",
"=",
"@parsed",
"[",
":clients",
"]",
".",
"slice",
"(",
"0",
",",
"@config",
"[",
":clients",
"]",
"[",
":top",
"]",
")",
"# top X clients",
"top",
".",
"each",
"do",
"|",
"client",
"|",
"retdict",
"[",
":top",
"]",
"<<",
"{",
"name",
":",
"client",
"[",
"1",
"]",
"[",
":name",
"]",
",",
"url",
":",
"client",
"[",
"1",
"]",
"[",
":url",
"]",
",",
"count",
":",
"client",
"[",
"1",
"]",
"[",
":count",
"]",
",",
"percentage",
":",
"(",
"client",
"[",
"1",
"]",
"[",
":count",
"]",
"*",
"100",
"/",
"@parsed",
"[",
":tweet_count",
"]",
".",
"to_f",
")",
".",
"round",
"(",
"2",
")",
"}",
"end",
"nottop",
"=",
"@parsed",
"[",
":clients",
"]",
".",
"slice",
"(",
"@config",
"[",
":clients",
"]",
"[",
":top",
"]",
",",
"@config",
"[",
":clients",
"]",
"[",
":notop",
"]",
")",
"# not in the top X",
"unless",
"nottop",
".",
"nil?",
"nottop",
".",
"each",
"do",
"|",
"client",
"|",
"client",
"[",
"1",
"]",
".",
"delete",
"(",
":example",
")",
"retdict",
"[",
":nottop",
"]",
"<<",
"{",
"name",
":",
"client",
"[",
"1",
"]",
"[",
":name",
"]",
",",
"url",
":",
"client",
"[",
"1",
"]",
"[",
":url",
"]",
",",
"count",
":",
"client",
"[",
"1",
"]",
"[",
":count",
"]",
",",
"percentage",
":",
"(",
"client",
"[",
"1",
"]",
"[",
":count",
"]",
"*",
"100",
"/",
"@parsed",
"[",
":tweet_count",
"]",
".",
"to_f",
")",
".",
"round",
"(",
"2",
")",
"}",
"end",
"end",
"end",
"retdict",
"end"
] | Returns an array with the clients which can be easily used within ERB. | [
"Returns",
"an",
"array",
"with",
"the",
"clients",
"which",
"can",
"be",
"easily",
"used",
"within",
"ERB",
"."
] | e652fb8966dfcd32968789af75e8d5a4f63134ec | https://github.com/nilsding/Empyrean/blob/e652fb8966dfcd32968789af75e8d5a4f63134ec/lib/empyrean/templaterenderer.rb#L139-L172 | train |
maxjacobson/todo_lint | lib/todo_lint/file_finder.rb | TodoLint.FileFinder.list | def list(*extensions)
all_files.keep_if do |filename|
extensions.include?(Pathname.new(filename).extname)
end
all_files.reject! { |file| excluded_file?(file) }
all_files
end | ruby | def list(*extensions)
all_files.keep_if do |filename|
extensions.include?(Pathname.new(filename).extname)
end
all_files.reject! { |file| excluded_file?(file) }
all_files
end | [
"def",
"list",
"(",
"*",
"extensions",
")",
"all_files",
".",
"keep_if",
"do",
"|",
"filename",
"|",
"extensions",
".",
"include?",
"(",
"Pathname",
".",
"new",
"(",
"filename",
")",
".",
"extname",
")",
"end",
"all_files",
".",
"reject!",
"{",
"|",
"file",
"|",
"excluded_file?",
"(",
"file",
")",
"}",
"all_files",
"end"
] | Instantiate a FileFinder with the path to a folder
@example
FileFinder.new("/Users/max/src/layabout")
@api public
Absolute paths to all the files with the provided extensions
@example
FileFinder.new("/Users/max/src/layabout").list(".rb", ".coffee")
@api public
@return [Array<String>] | [
"Instantiate",
"a",
"FileFinder",
"with",
"the",
"path",
"to",
"a",
"folder"
] | 0d1061383ea205ef4c74edc64568e308ac1af990 | https://github.com/maxjacobson/todo_lint/blob/0d1061383ea205ef4c74edc64568e308ac1af990/lib/todo_lint/file_finder.rb#L22-L28 | train |
maxjacobson/todo_lint | lib/todo_lint/file_finder.rb | TodoLint.FileFinder.excluded_file? | def excluded_file?(file)
full_path = File.expand_path(file)
options.fetch(:excluded_files) { [] }.any? do |file_to_exclude|
File.fnmatch(file_to_exclude, full_path)
end
end | ruby | def excluded_file?(file)
full_path = File.expand_path(file)
options.fetch(:excluded_files) { [] }.any? do |file_to_exclude|
File.fnmatch(file_to_exclude, full_path)
end
end | [
"def",
"excluded_file?",
"(",
"file",
")",
"full_path",
"=",
"File",
".",
"expand_path",
"(",
"file",
")",
"options",
".",
"fetch",
"(",
":excluded_files",
")",
"{",
"[",
"]",
"}",
".",
"any?",
"do",
"|",
"file_to_exclude",
"|",
"File",
".",
"fnmatch",
"(",
"file_to_exclude",
",",
"full_path",
")",
"end",
"end"
] | Check if this file has been excluded
@api private
@return [Boolean] | [
"Check",
"if",
"this",
"file",
"has",
"been",
"excluded"
] | 0d1061383ea205ef4c74edc64568e308ac1af990 | https://github.com/maxjacobson/todo_lint/blob/0d1061383ea205ef4c74edc64568e308ac1af990/lib/todo_lint/file_finder.rb#L51-L56 | train |
nathansobo/prequel | lib/prequel/errors.rb | Prequel.Errors.full_messages | def full_messages
inject([]) do |m, kv|
att, errors = *kv
errors.each {|e| m << "#{e}"}
m
end
end | ruby | def full_messages
inject([]) do |m, kv|
att, errors = *kv
errors.each {|e| m << "#{e}"}
m
end
end | [
"def",
"full_messages",
"inject",
"(",
"[",
"]",
")",
"do",
"|",
"m",
",",
"kv",
"|",
"att",
",",
"errors",
"=",
"kv",
"errors",
".",
"each",
"{",
"|",
"e",
"|",
"m",
"<<",
"\"#{e}\"",
"}",
"m",
"end",
"end"
] | Returns an array of fully-formatted error messages.
errors.full_messages
# => ['name is not valid',
# 'hometown is not at least 2 letters'] | [
"Returns",
"an",
"array",
"of",
"fully",
"-",
"formatted",
"error",
"messages",
"."
] | 5133dceb7af0b34caf38f4804c2951c043d89937 | https://github.com/nathansobo/prequel/blob/5133dceb7af0b34caf38f4804c2951c043d89937/lib/prequel/errors.rb#L37-L43 | train |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.