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
razor-x/config_curator
lib/config_curator/collection.rb
ConfigCurator.Collection.create_unit
def create_unit(type, attributes: {}) "#{self.class.name.split('::').first}::#{type.to_s.camelize}".constantize .new(options: unit_options, logger: logger).tap do |unit| {src: :source, dst: :destination}.each do |k, v| unit.send "#{v}=".to_sym, attributes[k] unless attributes[k].nil? end UNIT_ATTRIBUTES[type].each do |v| unit.send "#{v}=".to_sym, defaults[v] unless defaults[v].nil? unit.send "#{v}=".to_sym, attributes[v] unless attributes[v].nil? end end end
ruby
def create_unit(type, attributes: {}) "#{self.class.name.split('::').first}::#{type.to_s.camelize}".constantize .new(options: unit_options, logger: logger).tap do |unit| {src: :source, dst: :destination}.each do |k, v| unit.send "#{v}=".to_sym, attributes[k] unless attributes[k].nil? end UNIT_ATTRIBUTES[type].each do |v| unit.send "#{v}=".to_sym, defaults[v] unless defaults[v].nil? unit.send "#{v}=".to_sym, attributes[v] unless attributes[v].nil? end end end
[ "def", "create_unit", "(", "type", ",", "attributes", ":", "{", "}", ")", "\"#{self.class.name.split('::').first}::#{type.to_s.camelize}\"", ".", "constantize", ".", "new", "(", "options", ":", "unit_options", ",", "logger", ":", "logger", ")", ".", "tap", "do", "|", "unit", "|", "{", "src", ":", ":source", ",", "dst", ":", ":destination", "}", ".", "each", "do", "|", "k", ",", "v", "|", "unit", ".", "send", "\"#{v}=\"", ".", "to_sym", ",", "attributes", "[", "k", "]", "unless", "attributes", "[", "k", "]", ".", "nil?", "end", "UNIT_ATTRIBUTES", "[", "type", "]", ".", "each", "do", "|", "v", "|", "unit", ".", "send", "\"#{v}=\"", ".", "to_sym", ",", "defaults", "[", "v", "]", "unless", "defaults", "[", "v", "]", ".", "nil?", "unit", ".", "send", "\"#{v}=\"", ".", "to_sym", ",", "attributes", "[", "v", "]", "unless", "attributes", "[", "v", "]", ".", "nil?", "end", "end", "end" ]
Creates a new unit object for the collection. @param type [Symbol] a unit type in {UNIT_TYPES} @param attributes [Hash] attributes for the unit from {UNIT_ATTRIBUTES} @return [Unit] the unit object of the appropriate subclass
[ "Creates", "a", "new", "unit", "object", "for", "the", "collection", "." ]
b0c0742ba0c36acf66de3eafd23a7d17b210036b
https://github.com/razor-x/config_curator/blob/b0c0742ba0c36acf66de3eafd23a7d17b210036b/lib/config_curator/collection.rb#L93-L105
train
razor-x/config_curator
lib/config_curator/collection.rb
ConfigCurator.Collection.unit_options
def unit_options options = {} return options unless manifest %i(root package_tool).each do |k| options[k] = manifest[k] unless manifest[k].nil? end options end
ruby
def unit_options options = {} return options unless manifest %i(root package_tool).each do |k| options[k] = manifest[k] unless manifest[k].nil? end options end
[ "def", "unit_options", "options", "=", "{", "}", "return", "options", "unless", "manifest", "%i(", "root", "package_tool", ")", ".", "each", "do", "|", "k", "|", "options", "[", "k", "]", "=", "manifest", "[", "k", "]", "unless", "manifest", "[", "k", "]", ".", "nil?", "end", "options", "end" ]
Load basic unit options from the manifest. @return [Hash] the options
[ "Load", "basic", "unit", "options", "from", "the", "manifest", "." ]
b0c0742ba0c36acf66de3eafd23a7d17b210036b
https://github.com/razor-x/config_curator/blob/b0c0742ba0c36acf66de3eafd23a7d17b210036b/lib/config_curator/collection.rb#L125-L132
train
razor-x/config_curator
lib/config_curator/collection.rb
ConfigCurator.Collection.install_unit
def install_unit(unit, type, quiet = false) success = unit.install logger.info do "Installed #{type_name(type)}: #{unit.source} => #{unit.destination_path}" end unless quiet || !success return true rescue Unit::InstallFailed => e logger.fatal { "Halting install! Install attempt failed for #{type_name(type)}: #{e}" } return false end
ruby
def install_unit(unit, type, quiet = false) success = unit.install logger.info do "Installed #{type_name(type)}: #{unit.source} => #{unit.destination_path}" end unless quiet || !success return true rescue Unit::InstallFailed => e logger.fatal { "Halting install! Install attempt failed for #{type_name(type)}: #{e}" } return false end
[ "def", "install_unit", "(", "unit", ",", "type", ",", "quiet", "=", "false", ")", "success", "=", "unit", ".", "install", "logger", ".", "info", "do", "\"Installed #{type_name(type)}: #{unit.source} => #{unit.destination_path}\"", "end", "unless", "quiet", "||", "!", "success", "return", "true", "rescue", "Unit", "::", "InstallFailed", "=>", "e", "logger", ".", "fatal", "{", "\"Halting install! Install attempt failed for #{type_name(type)}: #{e}\"", "}", "return", "false", "end" ]
Installs a unit. @param unit [Unit] the unit to install @param type [Symbol] the unit type @param quiet [Boolean] suppress some {#logger} output @return [Boolean] if unit was installed
[ "Installs", "a", "unit", "." ]
b0c0742ba0c36acf66de3eafd23a7d17b210036b
https://github.com/razor-x/config_curator/blob/b0c0742ba0c36acf66de3eafd23a7d17b210036b/lib/config_curator/collection.rb#L139-L149
train
razor-x/config_curator
lib/config_curator/collection.rb
ConfigCurator.Collection.install_unit?
def install_unit?(unit, type, quiet = false) unit.install? logger.info do "Testing install for #{type_name(type)}:" \ " #{unit.source} => #{unit.destination_path}" end unless quiet return true rescue Unit::InstallFailed => e logger.error { "Cannot install #{type_name(type)}: #{e}" } return false end
ruby
def install_unit?(unit, type, quiet = false) unit.install? logger.info do "Testing install for #{type_name(type)}:" \ " #{unit.source} => #{unit.destination_path}" end unless quiet return true rescue Unit::InstallFailed => e logger.error { "Cannot install #{type_name(type)}: #{e}" } return false end
[ "def", "install_unit?", "(", "unit", ",", "type", ",", "quiet", "=", "false", ")", "unit", ".", "install?", "logger", ".", "info", "do", "\"Testing install for #{type_name(type)}:\"", "\" #{unit.source} => #{unit.destination_path}\"", "end", "unless", "quiet", "return", "true", "rescue", "Unit", "::", "InstallFailed", "=>", "e", "logger", ".", "error", "{", "\"Cannot install #{type_name(type)}: #{e}\"", "}", "return", "false", "end" ]
Checks if a unit can be installed. @param unit [Unit] the unit to check @param type [Symbol] the unit type @param quiet [Boolean] suppress some {#logger} output @return [Boolean] if unit can be installed
[ "Checks", "if", "a", "unit", "can", "be", "installed", "." ]
b0c0742ba0c36acf66de3eafd23a7d17b210036b
https://github.com/razor-x/config_curator/blob/b0c0742ba0c36acf66de3eafd23a7d17b210036b/lib/config_curator/collection.rb#L156-L167
train
webzakimbo/bcome-kontrol
lib/objects/registry/command/shortcut.rb
Bcome::Registry::Command.Shortcut.execute
def execute(node, arguments) ## We'll add in arguments later if run_as_pseudo_tty? node.pseudo_tty command else node.run command end rescue Interrupt puts "\nExiting gracefully from interrupt\n".warning end
ruby
def execute(node, arguments) ## We'll add in arguments later if run_as_pseudo_tty? node.pseudo_tty command else node.run command end rescue Interrupt puts "\nExiting gracefully from interrupt\n".warning end
[ "def", "execute", "(", "node", ",", "arguments", ")", "if", "run_as_pseudo_tty?", "node", ".", "pseudo_tty", "command", "else", "node", ".", "run", "command", "end", "rescue", "Interrupt", "puts", "\"\\nExiting gracefully from interrupt\\n\"", ".", "warning", "end" ]
In which the bcome context is a shortcut to a more complex command
[ "In", "which", "the", "bcome", "context", "is", "a", "shortcut", "to", "a", "more", "complex", "command" ]
59129cc7c8bb6c39e457abed783aa23c1d60cd05
https://github.com/webzakimbo/bcome-kontrol/blob/59129cc7c8bb6c39e457abed783aa23c1d60cd05/lib/objects/registry/command/shortcut.rb#L5-L13
train
blahah/assemblotron
lib/assemblotron/controller.rb
Assemblotron.Controller.process_options
def process_options options options = options.clone [:left, :right].each do |key| if options.key?(key) && !(options[key].nil?) options[key] = File.expand_path options[key] end end options end
ruby
def process_options options options = options.clone [:left, :right].each do |key| if options.key?(key) && !(options[key].nil?) options[key] = File.expand_path options[key] end end options end
[ "def", "process_options", "options", "options", "=", "options", ".", "clone", "[", ":left", ",", ":right", "]", ".", "each", "do", "|", "key", "|", "if", "options", ".", "key?", "(", "key", ")", "&&", "!", "(", "options", "[", "key", "]", ".", "nil?", ")", "options", "[", "key", "]", "=", "File", ".", "expand_path", "options", "[", "key", "]", "end", "end", "options", "end" ]
Creates a new Controller @return [Controller] the Controller initialize Cleanup and validity checking of global options
[ "Creates", "a", "new", "Controller" ]
475d59c72ba36ebb2799076a0009758d12fa1508
https://github.com/blahah/assemblotron/blob/475d59c72ba36ebb2799076a0009758d12fa1508/lib/assemblotron/controller.rb#L26-L34
train
blahah/assemblotron
lib/assemblotron/controller.rb
Assemblotron.Controller.run
def run if @options[:list_assemblers] puts @assemblerman.list_assemblers return elsif @options[:install_assemblers] @assemblerman.install_assemblers(@options[:install_assemblers]) return end if (@options[:left].nil? || @options[:right].nil?) logger.error "Reads must be provided with --left and --right" logger.error "Try --help for command-line help" exit(1) end unless (@options[:timelimit].nil?) logger.info "Time limit set to #{@options[:timelimit]}" end subsample_input res = @assemblerman.run_all_assemblers @options write_metadata res merge_assemblies res end
ruby
def run if @options[:list_assemblers] puts @assemblerman.list_assemblers return elsif @options[:install_assemblers] @assemblerman.install_assemblers(@options[:install_assemblers]) return end if (@options[:left].nil? || @options[:right].nil?) logger.error "Reads must be provided with --left and --right" logger.error "Try --help for command-line help" exit(1) end unless (@options[:timelimit].nil?) logger.info "Time limit set to #{@options[:timelimit]}" end subsample_input res = @assemblerman.run_all_assemblers @options write_metadata res merge_assemblies res end
[ "def", "run", "if", "@options", "[", ":list_assemblers", "]", "puts", "@assemblerman", ".", "list_assemblers", "return", "elsif", "@options", "[", ":install_assemblers", "]", "@assemblerman", ".", "install_assemblers", "(", "@options", "[", ":install_assemblers", "]", ")", "return", "end", "if", "(", "@options", "[", ":left", "]", ".", "nil?", "||", "@options", "[", ":right", "]", ".", "nil?", ")", "logger", ".", "error", "\"Reads must be provided with --left and --right\"", "logger", ".", "error", "\"Try --help for command-line help\"", "exit", "(", "1", ")", "end", "unless", "(", "@options", "[", ":timelimit", "]", ".", "nil?", ")", "logger", ".", "info", "\"Time limit set to #{@options[:timelimit]}\"", "end", "subsample_input", "res", "=", "@assemblerman", ".", "run_all_assemblers", "@options", "write_metadata", "res", "merge_assemblies", "res", "end" ]
Runs the program
[ "Runs", "the", "program" ]
475d59c72ba36ebb2799076a0009758d12fa1508
https://github.com/blahah/assemblotron/blob/475d59c72ba36ebb2799076a0009758d12fa1508/lib/assemblotron/controller.rb#L37-L62
train
blahah/assemblotron
lib/assemblotron/controller.rb
Assemblotron.Controller.init_settings
def init_settings s = Biopsy::Settings.instance s.set_defaults libdir = File.dirname(__FILE__) s.target_dir = [File.join(libdir, 'assemblers/')] s.objectives_dir = [File.join(libdir, 'objectives/')] logger.debug "initialised Biopsy settings" end
ruby
def init_settings s = Biopsy::Settings.instance s.set_defaults libdir = File.dirname(__FILE__) s.target_dir = [File.join(libdir, 'assemblers/')] s.objectives_dir = [File.join(libdir, 'objectives/')] logger.debug "initialised Biopsy settings" end
[ "def", "init_settings", "s", "=", "Biopsy", "::", "Settings", ".", "instance", "s", ".", "set_defaults", "libdir", "=", "File", ".", "dirname", "(", "__FILE__", ")", "s", ".", "target_dir", "=", "[", "File", ".", "join", "(", "libdir", ",", "'assemblers/'", ")", "]", "s", ".", "objectives_dir", "=", "[", "File", ".", "join", "(", "libdir", ",", "'objectives/'", ")", "]", "logger", ".", "debug", "\"initialised Biopsy settings\"", "end" ]
Initialise the Biopsy settings with defaults, setting target and objectiv directories to those provided with Assemblotron
[ "Initialise", "the", "Biopsy", "settings", "with", "defaults", "setting", "target", "and", "objectiv", "directories", "to", "those", "provided", "with", "Assemblotron" ]
475d59c72ba36ebb2799076a0009758d12fa1508
https://github.com/blahah/assemblotron/blob/475d59c72ba36ebb2799076a0009758d12fa1508/lib/assemblotron/controller.rb#L76-L83
train
blahah/assemblotron
lib/assemblotron/controller.rb
Assemblotron.Controller.write_metadata
def write_metadata res File.open(@options[:output_parameters], 'wb') do |f| f.write(JSON.pretty_generate(res)) end end
ruby
def write_metadata res File.open(@options[:output_parameters], 'wb') do |f| f.write(JSON.pretty_generate(res)) end end
[ "def", "write_metadata", "res", "File", ".", "open", "(", "@options", "[", ":output_parameters", "]", ",", "'wb'", ")", "do", "|", "f", "|", "f", ".", "write", "(", "JSON", ".", "pretty_generate", "(", "res", ")", ")", "end", "end" ]
Write out metadata from the optimisation run
[ "Write", "out", "metadata", "from", "the", "optimisation", "run" ]
475d59c72ba36ebb2799076a0009758d12fa1508
https://github.com/blahah/assemblotron/blob/475d59c72ba36ebb2799076a0009758d12fa1508/lib/assemblotron/controller.rb#L86-L90
train
blahah/assemblotron
lib/assemblotron/controller.rb
Assemblotron.Controller.subsample_input
def subsample_input if @options[:skip_subsample] logger.info "Skipping subsample step (--skip-subsample is on)" @options[:left_subset] = @options[:left] @options[:right_subset] = @options[:right] return end logger.info "Subsampling reads" seed = @options[:seed] seed = Time.now.to_i if seed == -1 logger.info "Using random seed #{seed}" l = @options[:left] r = @options[:right] size = @options[:subsample_size] sampler = Sampler.new if @options[:sampler] == "stream" ls, rs = sampler.sample_stream(l, r, size, seed) elsif @options[:sampler] == "graph" ls, rs = sampler.sample_graph(l, r, size, seed) else logger.error "sampler #{@options[:sampler]} was not a valid choice" logger.error "please user --help to see the options" exit 1 end @options[:left_subset] = ls @options[:right_subset] = rs end
ruby
def subsample_input if @options[:skip_subsample] logger.info "Skipping subsample step (--skip-subsample is on)" @options[:left_subset] = @options[:left] @options[:right_subset] = @options[:right] return end logger.info "Subsampling reads" seed = @options[:seed] seed = Time.now.to_i if seed == -1 logger.info "Using random seed #{seed}" l = @options[:left] r = @options[:right] size = @options[:subsample_size] sampler = Sampler.new if @options[:sampler] == "stream" ls, rs = sampler.sample_stream(l, r, size, seed) elsif @options[:sampler] == "graph" ls, rs = sampler.sample_graph(l, r, size, seed) else logger.error "sampler #{@options[:sampler]} was not a valid choice" logger.error "please user --help to see the options" exit 1 end @options[:left_subset] = ls @options[:right_subset] = rs end
[ "def", "subsample_input", "if", "@options", "[", ":skip_subsample", "]", "logger", ".", "info", "\"Skipping subsample step (--skip-subsample is on)\"", "@options", "[", ":left_subset", "]", "=", "@options", "[", ":left", "]", "@options", "[", ":right_subset", "]", "=", "@options", "[", ":right", "]", "return", "end", "logger", ".", "info", "\"Subsampling reads\"", "seed", "=", "@options", "[", ":seed", "]", "seed", "=", "Time", ".", "now", ".", "to_i", "if", "seed", "==", "-", "1", "logger", ".", "info", "\"Using random seed #{seed}\"", "l", "=", "@options", "[", ":left", "]", "r", "=", "@options", "[", ":right", "]", "size", "=", "@options", "[", ":subsample_size", "]", "sampler", "=", "Sampler", ".", "new", "if", "@options", "[", ":sampler", "]", "==", "\"stream\"", "ls", ",", "rs", "=", "sampler", ".", "sample_stream", "(", "l", ",", "r", ",", "size", ",", "seed", ")", "elsif", "@options", "[", ":sampler", "]", "==", "\"graph\"", "ls", ",", "rs", "=", "sampler", ".", "sample_graph", "(", "l", ",", "r", ",", "size", ",", "seed", ")", "else", "logger", ".", "error", "\"sampler #{@options[:sampler]} was not a valid choice\"", "logger", ".", "error", "\"please user --help to see the options\"", "exit", "1", "end", "@options", "[", ":left_subset", "]", "=", "ls", "@options", "[", ":right_subset", "]", "=", "rs", "end" ]
Run the subsampler on the input reads, storing the paths to the samples in the assembler_options hash.
[ "Run", "the", "subsampler", "on", "the", "input", "reads", "storing", "the", "paths", "to", "the", "samples", "in", "the", "assembler_options", "hash", "." ]
475d59c72ba36ebb2799076a0009758d12fa1508
https://github.com/blahah/assemblotron/blob/475d59c72ba36ebb2799076a0009758d12fa1508/lib/assemblotron/controller.rb#L95-L127
train
blahah/assemblotron
lib/assemblotron/controller.rb
Assemblotron.Controller.merge_assemblies
def merge_assemblies res l = @options[:left] r = @options[:right] transfuse = Transfuse::Transfuse.new(@options[:threads], false) assemblies = res.each_value.map { |assembler| assember[:final] } scores = transfuse.transrate(assemblies, l, r) filtered = transfuse.filter(assemblies, scores) cat = transfuse.concatenate filtered transfuse.load_fasta cat clusters = transfuse.cluster cat best = transfuse.select_contigs(clusters, scores) transfuse.output_contigs(best, cat, 'merged.fa') end
ruby
def merge_assemblies res l = @options[:left] r = @options[:right] transfuse = Transfuse::Transfuse.new(@options[:threads], false) assemblies = res.each_value.map { |assembler| assember[:final] } scores = transfuse.transrate(assemblies, l, r) filtered = transfuse.filter(assemblies, scores) cat = transfuse.concatenate filtered transfuse.load_fasta cat clusters = transfuse.cluster cat best = transfuse.select_contigs(clusters, scores) transfuse.output_contigs(best, cat, 'merged.fa') end
[ "def", "merge_assemblies", "res", "l", "=", "@options", "[", ":left", "]", "r", "=", "@options", "[", ":right", "]", "transfuse", "=", "Transfuse", "::", "Transfuse", ".", "new", "(", "@options", "[", ":threads", "]", ",", "false", ")", "assemblies", "=", "res", ".", "each_value", ".", "map", "{", "|", "assembler", "|", "assember", "[", ":final", "]", "}", "scores", "=", "transfuse", ".", "transrate", "(", "assemblies", ",", "l", ",", "r", ")", "filtered", "=", "transfuse", ".", "filter", "(", "assemblies", ",", "scores", ")", "cat", "=", "transfuse", ".", "concatenate", "filtered", "transfuse", ".", "load_fasta", "cat", "clusters", "=", "transfuse", ".", "cluster", "cat", "best", "=", "transfuse", ".", "select_contigs", "(", "clusters", ",", "scores", ")", "transfuse", ".", "output_contigs", "(", "best", ",", "cat", ",", "'merged.fa'", ")", "end" ]
Merge the final assemblies
[ "Merge", "the", "final", "assemblies" ]
475d59c72ba36ebb2799076a0009758d12fa1508
https://github.com/blahah/assemblotron/blob/475d59c72ba36ebb2799076a0009758d12fa1508/lib/assemblotron/controller.rb#L130-L145
train
blahah/biopsy
lib/biopsy/settings.rb
Biopsy.Settings.all_settings
def all_settings settings = {} instance_variables.each do |var| key = var[1..-1] settings[key] = self.instance_variable_get(var) end settings end
ruby
def all_settings settings = {} instance_variables.each do |var| key = var[1..-1] settings[key] = self.instance_variable_get(var) end settings end
[ "def", "all_settings", "settings", "=", "{", "}", "instance_variables", ".", "each", "do", "|", "var", "|", "key", "=", "var", "[", "1", "..", "-", "1", "]", "settings", "[", "key", "]", "=", "self", ".", "instance_variable_get", "(", "var", ")", "end", "settings", "end" ]
Returns a hash of the settings
[ "Returns", "a", "hash", "of", "the", "settings" ]
e46f3d1c75de4da2ec47a377f7e4f0e16a8e03d2
https://github.com/blahah/biopsy/blob/e46f3d1c75de4da2ec47a377f7e4f0e16a8e03d2/lib/biopsy/settings.rb#L79-L86
train
JulianNicholls/gosu_enhanced-gem
lib/gosu_enhanced/enhanced.rb
Gosu.Window.draw_rectangle
def draw_rectangle(point, size, z_index, colour) left = point.x top = point.y width = size.width height = size.height draw_quad( left, top, colour, left + width, top, colour, left + width, top + height, colour, left, top + height, colour, z_index) end
ruby
def draw_rectangle(point, size, z_index, colour) left = point.x top = point.y width = size.width height = size.height draw_quad( left, top, colour, left + width, top, colour, left + width, top + height, colour, left, top + height, colour, z_index) end
[ "def", "draw_rectangle", "(", "point", ",", "size", ",", "z_index", ",", "colour", ")", "left", "=", "point", ".", "x", "top", "=", "point", ".", "y", "width", "=", "size", ".", "width", "height", "=", "size", ".", "height", "draw_quad", "(", "left", ",", "top", ",", "colour", ",", "left", "+", "width", ",", "top", ",", "colour", ",", "left", "+", "width", ",", "top", "+", "height", ",", "colour", ",", "left", ",", "top", "+", "height", ",", "colour", ",", "z_index", ")", "end" ]
Simplify drawing a rectangle in a single colour. * +point+ [Point] Top left corner * +size+ [Size] Width and Height * +z_index+ [Fixnum] Z-order * +colour+ [Gosu::Color] Colour of rectangle
[ "Simplify", "drawing", "a", "rectangle", "in", "a", "single", "colour", "." ]
07b5258458c4c3c315f697c8d5da839a93eb2c67
https://github.com/JulianNicholls/gosu_enhanced-gem/blob/07b5258458c4c3c315f697c8d5da839a93eb2c67/lib/gosu_enhanced/enhanced.rb#L14-L26
train
JulianNicholls/gosu_enhanced-gem
lib/gosu_enhanced/enhanced.rb
Gosu.Window.draw_simple_line
def draw_simple_line(p1, p2, z_index, colour) draw_line(p1.x, p1.y, colour, p2.x, p2.y, colour, z_index) end
ruby
def draw_simple_line(p1, p2, z_index, colour) draw_line(p1.x, p1.y, colour, p2.x, p2.y, colour, z_index) end
[ "def", "draw_simple_line", "(", "p1", ",", "p2", ",", "z_index", ",", "colour", ")", "draw_line", "(", "p1", ".", "x", ",", "p1", ".", "y", ",", "colour", ",", "p2", ".", "x", ",", "p2", ".", "y", ",", "colour", ",", "z_index", ")", "end" ]
Simplify drawing a line. There are dire warnings in the Gosu documentation for draw_line() which suggest that line drawing should only be done for debugging purposes. * +p1+ [Point] Beginning point * +p2+ [Point] Endpoint * +z_index+ [Fixnum] Z-order * +colour+ [Gosu::Color] Colour of line
[ "Simplify", "drawing", "a", "line", "." ]
07b5258458c4c3c315f697c8d5da839a93eb2c67
https://github.com/JulianNicholls/gosu_enhanced-gem/blob/07b5258458c4c3c315f697c8d5da839a93eb2c67/lib/gosu_enhanced/enhanced.rb#L38-L40
train
JulianNicholls/gosu_enhanced-gem
lib/gosu_enhanced/enhanced.rb
Gosu.Font.centred_in
def centred_in(text, rect) size = measure(text) Point((rect.width - size.width) / 2, (rect.height - size.height) / 2) end
ruby
def centred_in(text, rect) size = measure(text) Point((rect.width - size.width) / 2, (rect.height - size.height) / 2) end
[ "def", "centred_in", "(", "text", ",", "rect", ")", "size", "=", "measure", "(", "text", ")", "Point", "(", "(", "rect", ".", "width", "-", "size", ".", "width", ")", "/", "2", ",", "(", "rect", ".", "height", "-", "size", ".", "height", ")", "/", "2", ")", "end" ]
Return the co-ordnates needed to place a given string in the centre of an area, both vertically and horizontally. * +text+ [String] String to centre * +rect+ [Size] Rectangular area size return:: [Point] The point to write the string, expressed as an offset from the top-left corner of the rectangle.
[ "Return", "the", "co", "-", "ordnates", "needed", "to", "place", "a", "given", "string", "in", "the", "centre", "of", "an", "area", "both", "vertically", "and", "horizontally", "." ]
07b5258458c4c3c315f697c8d5da839a93eb2c67
https://github.com/JulianNicholls/gosu_enhanced-gem/blob/07b5258458c4c3c315f697c8d5da839a93eb2c67/lib/gosu_enhanced/enhanced.rb#L67-L71
train
kwi/BrB
lib/brb/request.rb
BrB.Request.new_brb_out_request
def new_brb_out_request(meth, *args, &blck) Thread.current[:brb_nb_out] ||= 0 Thread.current[:brb_nb_out] += 1 raise BrBCallbackWithBlockingMethodException.new if is_brb_request_blocking?(meth) and block_given? block = (is_brb_request_blocking?(meth) or block_given?) ? Thread.current.to_s.to_sym : nil if block args << block args << Thread.current[:brb_nb_out] end if block_given? # Simulate a method with _block in order to make BrB send the answer meth = "#{meth}_block".to_sym end args.size > 0 ? brb_send([MessageRequestCode, meth, args]) : brb_send([MessageRequestCode, meth]) if block_given? # Declare the callback declare_callback(block, Thread.current[:brb_nb_out], &blck) elsif block # Block until the request return #TimeMonitor.instance.watch_thread!(@timeout_rcv_value || 45) begin r = recv(block, Thread.current[:brb_nb_out], &blck) rescue Exception => e raise e ensure #TimeMonitor.instance.remove_thread! end if r.kind_of? Exception raise r end return r end nil end
ruby
def new_brb_out_request(meth, *args, &blck) Thread.current[:brb_nb_out] ||= 0 Thread.current[:brb_nb_out] += 1 raise BrBCallbackWithBlockingMethodException.new if is_brb_request_blocking?(meth) and block_given? block = (is_brb_request_blocking?(meth) or block_given?) ? Thread.current.to_s.to_sym : nil if block args << block args << Thread.current[:brb_nb_out] end if block_given? # Simulate a method with _block in order to make BrB send the answer meth = "#{meth}_block".to_sym end args.size > 0 ? brb_send([MessageRequestCode, meth, args]) : brb_send([MessageRequestCode, meth]) if block_given? # Declare the callback declare_callback(block, Thread.current[:brb_nb_out], &blck) elsif block # Block until the request return #TimeMonitor.instance.watch_thread!(@timeout_rcv_value || 45) begin r = recv(block, Thread.current[:brb_nb_out], &blck) rescue Exception => e raise e ensure #TimeMonitor.instance.remove_thread! end if r.kind_of? Exception raise r end return r end nil end
[ "def", "new_brb_out_request", "(", "meth", ",", "*", "args", ",", "&", "blck", ")", "Thread", ".", "current", "[", ":brb_nb_out", "]", "||=", "0", "Thread", ".", "current", "[", ":brb_nb_out", "]", "+=", "1", "raise", "BrBCallbackWithBlockingMethodException", ".", "new", "if", "is_brb_request_blocking?", "(", "meth", ")", "and", "block_given?", "block", "=", "(", "is_brb_request_blocking?", "(", "meth", ")", "or", "block_given?", ")", "?", "Thread", ".", "current", ".", "to_s", ".", "to_sym", ":", "nil", "if", "block", "args", "<<", "block", "args", "<<", "Thread", ".", "current", "[", ":brb_nb_out", "]", "end", "if", "block_given?", "meth", "=", "\"#{meth}_block\"", ".", "to_sym", "end", "args", ".", "size", ">", "0", "?", "brb_send", "(", "[", "MessageRequestCode", ",", "meth", ",", "args", "]", ")", ":", "brb_send", "(", "[", "MessageRequestCode", ",", "meth", "]", ")", "if", "block_given?", "declare_callback", "(", "block", ",", "Thread", ".", "current", "[", ":brb_nb_out", "]", ",", "&", "blck", ")", "elsif", "block", "begin", "r", "=", "recv", "(", "block", ",", "Thread", ".", "current", "[", ":brb_nb_out", "]", ",", "&", "blck", ")", "rescue", "Exception", "=>", "e", "raise", "e", "ensure", "end", "if", "r", ".", "kind_of?", "Exception", "raise", "r", "end", "return", "r", "end", "nil", "end" ]
Execute a request on a distant object
[ "Execute", "a", "request", "on", "a", "distant", "object" ]
1ae0c82fc44759627f2145fd9e02092b37e19d69
https://github.com/kwi/BrB/blob/1ae0c82fc44759627f2145fd9e02092b37e19d69/lib/brb/request.rb#L16-L56
train
kwi/BrB
lib/brb/request.rb
BrB.Request.new_brb_in_request
def new_brb_in_request(meth, *args) if is_brb_request_blocking?(meth) m = meth.to_s m = m[0, m.size - 6].to_sym idrequest = args.pop thread = args.pop begin r = ((args.size > 0) ? @object.send(m, *args) : @object.send(m)) brb_send([ReturnCode, r, thread, idrequest]) rescue Exception => e brb_send([ReturnCode, e, thread, idrequest]) BrB.logger.error e.to_s BrB.logger.error e.backtrace.join("\n") #raise e end else begin (args.size > 0) ? @object.send(meth, *args) : @object.send(meth) rescue Exception => e BrB.logger.error "#{e.to_s} => By calling #{meth} on #{@object.class} with args : #{args.inspect}" BrB.logger.error e.backtrace.join("\n") raise e end end end
ruby
def new_brb_in_request(meth, *args) if is_brb_request_blocking?(meth) m = meth.to_s m = m[0, m.size - 6].to_sym idrequest = args.pop thread = args.pop begin r = ((args.size > 0) ? @object.send(m, *args) : @object.send(m)) brb_send([ReturnCode, r, thread, idrequest]) rescue Exception => e brb_send([ReturnCode, e, thread, idrequest]) BrB.logger.error e.to_s BrB.logger.error e.backtrace.join("\n") #raise e end else begin (args.size > 0) ? @object.send(meth, *args) : @object.send(meth) rescue Exception => e BrB.logger.error "#{e.to_s} => By calling #{meth} on #{@object.class} with args : #{args.inspect}" BrB.logger.error e.backtrace.join("\n") raise e end end end
[ "def", "new_brb_in_request", "(", "meth", ",", "*", "args", ")", "if", "is_brb_request_blocking?", "(", "meth", ")", "m", "=", "meth", ".", "to_s", "m", "=", "m", "[", "0", ",", "m", ".", "size", "-", "6", "]", ".", "to_sym", "idrequest", "=", "args", ".", "pop", "thread", "=", "args", ".", "pop", "begin", "r", "=", "(", "(", "args", ".", "size", ">", "0", ")", "?", "@object", ".", "send", "(", "m", ",", "*", "args", ")", ":", "@object", ".", "send", "(", "m", ")", ")", "brb_send", "(", "[", "ReturnCode", ",", "r", ",", "thread", ",", "idrequest", "]", ")", "rescue", "Exception", "=>", "e", "brb_send", "(", "[", "ReturnCode", ",", "e", ",", "thread", ",", "idrequest", "]", ")", "BrB", ".", "logger", ".", "error", "e", ".", "to_s", "BrB", ".", "logger", ".", "error", "e", ".", "backtrace", ".", "join", "(", "\"\\n\"", ")", "end", "else", "begin", "(", "args", ".", "size", ">", "0", ")", "?", "@object", ".", "send", "(", "meth", ",", "*", "args", ")", ":", "@object", ".", "send", "(", "meth", ")", "rescue", "Exception", "=>", "e", "BrB", ".", "logger", ".", "error", "\"#{e.to_s} => By calling #{meth} on #{@object.class} with args : #{args.inspect}\"", "BrB", ".", "logger", ".", "error", "e", ".", "backtrace", ".", "join", "(", "\"\\n\"", ")", "raise", "e", "end", "end", "end" ]
Execute a request on the local object
[ "Execute", "a", "request", "on", "the", "local", "object" ]
1ae0c82fc44759627f2145fd9e02092b37e19d69
https://github.com/kwi/BrB/blob/1ae0c82fc44759627f2145fd9e02092b37e19d69/lib/brb/request.rb#L59-L89
train
ManageIQ/polisher
lib/polisher/gem/diff.rb
Polisher.GemDiff.diff
def diff(other) require_dep! 'awesome_spawn' require_cmd! diff_cmd out = nil begin this_dir = unpack other_dir = if other.is_a?(Polisher::Gem) other.unpack elsif other.is_a?(Polisher::Git::Repo) other.path else other end result = AwesomeSpawn.run("#{diff_cmd} -r #{this_dir} #{other_dir}") out = result.output.gsub("#{this_dir}", 'a').gsub("#{other_dir}", 'b') rescue ensure FileUtils.rm_rf this_dir unless this_dir.nil? FileUtils.rm_rf other_dir unless other_dir.nil? || !other.is_a?(Polisher::Gem) end out end
ruby
def diff(other) require_dep! 'awesome_spawn' require_cmd! diff_cmd out = nil begin this_dir = unpack other_dir = if other.is_a?(Polisher::Gem) other.unpack elsif other.is_a?(Polisher::Git::Repo) other.path else other end result = AwesomeSpawn.run("#{diff_cmd} -r #{this_dir} #{other_dir}") out = result.output.gsub("#{this_dir}", 'a').gsub("#{other_dir}", 'b') rescue ensure FileUtils.rm_rf this_dir unless this_dir.nil? FileUtils.rm_rf other_dir unless other_dir.nil? || !other.is_a?(Polisher::Gem) end out end
[ "def", "diff", "(", "other", ")", "require_dep!", "'awesome_spawn'", "require_cmd!", "diff_cmd", "out", "=", "nil", "begin", "this_dir", "=", "unpack", "other_dir", "=", "if", "other", ".", "is_a?", "(", "Polisher", "::", "Gem", ")", "other", ".", "unpack", "elsif", "other", ".", "is_a?", "(", "Polisher", "::", "Git", "::", "Repo", ")", "other", ".", "path", "else", "other", "end", "result", "=", "AwesomeSpawn", ".", "run", "(", "\"#{diff_cmd} -r #{this_dir} #{other_dir}\"", ")", "out", "=", "result", ".", "output", ".", "gsub", "(", "\"#{this_dir}\"", ",", "'a'", ")", ".", "gsub", "(", "\"#{other_dir}\"", ",", "'b'", ")", "rescue", "ensure", "FileUtils", ".", "rm_rf", "this_dir", "unless", "this_dir", ".", "nil?", "FileUtils", ".", "rm_rf", "other_dir", "unless", "other_dir", ".", "nil?", "||", "!", "other", ".", "is_a?", "(", "Polisher", "::", "Gem", ")", "end", "out", "end" ]
Return diff of content in this gem against other
[ "Return", "diff", "of", "content", "in", "this", "gem", "against", "other" ]
8c19023c72573999c9dc53ec2e2a3eef11a9531e
https://github.com/ManageIQ/polisher/blob/8c19023c72573999c9dc53ec2e2a3eef11a9531e/lib/polisher/gem/diff.rb#L12-L37
train
xtremelabs/xl-passbook-ruby
app/controllers/passbook/registrations_controller.rb
Passbook.RegistrationsController.push_token
def push_token return params[:pushToken] if params.include?(:pushToken) if request && request.body request.body.rewind json_body = JSON.parse(request.body.read) if json_body['pushToken'] json_body['pushToken'] end end end
ruby
def push_token return params[:pushToken] if params.include?(:pushToken) if request && request.body request.body.rewind json_body = JSON.parse(request.body.read) if json_body['pushToken'] json_body['pushToken'] end end end
[ "def", "push_token", "return", "params", "[", ":pushToken", "]", "if", "params", ".", "include?", "(", ":pushToken", ")", "if", "request", "&&", "request", ".", "body", "request", ".", "body", ".", "rewind", "json_body", "=", "JSON", ".", "parse", "(", "request", ".", "body", ".", "read", ")", "if", "json_body", "[", "'pushToken'", "]", "json_body", "[", "'pushToken'", "]", "end", "end", "end" ]
Convienience method for parsing the pushToken out of a JSON POST body
[ "Convienience", "method", "for", "parsing", "the", "pushToken", "out", "of", "a", "JSON", "POST", "body" ]
01ef5f5461258287b8067a00df1f15f00133c865
https://github.com/xtremelabs/xl-passbook-ruby/blob/01ef5f5461258287b8067a00df1f15f00133c865/app/controllers/passbook/registrations_controller.rb#L158-L167
train
evgenyneu/siba
lib/siba/generator.rb
Siba.Generator.generate
def generate siba_file.run_this do file_path = @name.gsub /\.yml$/, "" file_path += ".yml" file_path = siba_file.file_expand_path file_path if siba_file.file_file?(file_path) || siba_file.file_directory?(file_path) raise Siba::Error, "Options file already exists: #{file_path}" end options_data = [] Siba::Plugins::PLUGINS_HASH.each do |category, types| type = nil if types.size > 1 max_type_length = types.keys.max do |a,b| a.length <=> b.length end.length + 5 siba_kernel.puts "\nChoose #{category} plugin:" types.keys.each_index do |i| type = types.keys[i] siba_kernel.puts " #{i+1}. #{Siba::Plugins.plugin_type_and_description(category, type, max_type_length)}" end type = Siba::Generator.get_plugin_user_choice types.keys if type.nil? siba_kernel.puts "Cancelled by user" return end unless Siba::InstalledPlugins.installed? category, type siba_kernel.puts Siba::InstalledPlugins.install_gem_message(category, type) return end else type = types.keys.first end options = Siba::Generator.load_plugin_yaml_content category, type unless options =~ /^\s*type:/ options = "type: #{type}\n" + options end options.gsub! /^/, " " options = "#{category}:\n" + options options_data << options end file_data = options_data.join("\n") file_data = "# SIBA options file\n" + file_data dest_dir = File.dirname file_path siba_file.file_utils_mkpath(dest_dir) unless siba_file.file_directory?(dest_dir) Siba::FileHelper.write file_path, file_data file_path end end
ruby
def generate siba_file.run_this do file_path = @name.gsub /\.yml$/, "" file_path += ".yml" file_path = siba_file.file_expand_path file_path if siba_file.file_file?(file_path) || siba_file.file_directory?(file_path) raise Siba::Error, "Options file already exists: #{file_path}" end options_data = [] Siba::Plugins::PLUGINS_HASH.each do |category, types| type = nil if types.size > 1 max_type_length = types.keys.max do |a,b| a.length <=> b.length end.length + 5 siba_kernel.puts "\nChoose #{category} plugin:" types.keys.each_index do |i| type = types.keys[i] siba_kernel.puts " #{i+1}. #{Siba::Plugins.plugin_type_and_description(category, type, max_type_length)}" end type = Siba::Generator.get_plugin_user_choice types.keys if type.nil? siba_kernel.puts "Cancelled by user" return end unless Siba::InstalledPlugins.installed? category, type siba_kernel.puts Siba::InstalledPlugins.install_gem_message(category, type) return end else type = types.keys.first end options = Siba::Generator.load_plugin_yaml_content category, type unless options =~ /^\s*type:/ options = "type: #{type}\n" + options end options.gsub! /^/, " " options = "#{category}:\n" + options options_data << options end file_data = options_data.join("\n") file_data = "# SIBA options file\n" + file_data dest_dir = File.dirname file_path siba_file.file_utils_mkpath(dest_dir) unless siba_file.file_directory?(dest_dir) Siba::FileHelper.write file_path, file_data file_path end end
[ "def", "generate", "siba_file", ".", "run_this", "do", "file_path", "=", "@name", ".", "gsub", "/", "\\.", "/", ",", "\"\"", "file_path", "+=", "\".yml\"", "file_path", "=", "siba_file", ".", "file_expand_path", "file_path", "if", "siba_file", ".", "file_file?", "(", "file_path", ")", "||", "siba_file", ".", "file_directory?", "(", "file_path", ")", "raise", "Siba", "::", "Error", ",", "\"Options file already exists: #{file_path}\"", "end", "options_data", "=", "[", "]", "Siba", "::", "Plugins", "::", "PLUGINS_HASH", ".", "each", "do", "|", "category", ",", "types", "|", "type", "=", "nil", "if", "types", ".", "size", ">", "1", "max_type_length", "=", "types", ".", "keys", ".", "max", "do", "|", "a", ",", "b", "|", "a", ".", "length", "<=>", "b", ".", "length", "end", ".", "length", "+", "5", "siba_kernel", ".", "puts", "\"\\nChoose #{category} plugin:\"", "types", ".", "keys", ".", "each_index", "do", "|", "i", "|", "type", "=", "types", ".", "keys", "[", "i", "]", "siba_kernel", ".", "puts", "\" #{i+1}. #{Siba::Plugins.plugin_type_and_description(category, type, max_type_length)}\"", "end", "type", "=", "Siba", "::", "Generator", ".", "get_plugin_user_choice", "types", ".", "keys", "if", "type", ".", "nil?", "siba_kernel", ".", "puts", "\"Cancelled by user\"", "return", "end", "unless", "Siba", "::", "InstalledPlugins", ".", "installed?", "category", ",", "type", "siba_kernel", ".", "puts", "Siba", "::", "InstalledPlugins", ".", "install_gem_message", "(", "category", ",", "type", ")", "return", "end", "else", "type", "=", "types", ".", "keys", ".", "first", "end", "options", "=", "Siba", "::", "Generator", ".", "load_plugin_yaml_content", "category", ",", "type", "unless", "options", "=~", "/", "\\s", "/", "options", "=", "\"type: #{type}\\n\"", "+", "options", "end", "options", ".", "gsub!", "/", "/", ",", "\" \"", "options", "=", "\"#{category}:\\n\"", "+", "options", "options_data", "<<", "options", "end", "file_data", "=", "options_data", ".", "join", "(", "\"\\n\"", ")", "file_data", "=", "\"# SIBA options file\\n\"", "+", "file_data", "dest_dir", "=", "File", ".", "dirname", "file_path", "siba_file", ".", "file_utils_mkpath", "(", "dest_dir", ")", "unless", "siba_file", ".", "file_directory?", "(", "dest_dir", ")", "Siba", "::", "FileHelper", ".", "write", "file_path", ",", "file_data", "file_path", "end", "end" ]
Generates yaml options file and returns its path
[ "Generates", "yaml", "options", "file", "and", "returns", "its", "path" ]
04cd0eca8222092c14ce4a662b48f5f113ffe6df
https://github.com/evgenyneu/siba/blob/04cd0eca8222092c14ce4a662b48f5f113ffe6df/lib/siba/generator.rb#L16-L70
train
ubcsanskrit/sanscript.rb
lib/sanscript/transliterate.rb
Sanscript.Transliterate.add_brahmic_scheme
def add_brahmic_scheme(name, scheme) name = name.to_sym scheme = scheme.deep_dup @schemes[name] = IceNine.deep_freeze(scheme) @brahmic_schemes.add(name) @scheme_names.add(name) scheme end
ruby
def add_brahmic_scheme(name, scheme) name = name.to_sym scheme = scheme.deep_dup @schemes[name] = IceNine.deep_freeze(scheme) @brahmic_schemes.add(name) @scheme_names.add(name) scheme end
[ "def", "add_brahmic_scheme", "(", "name", ",", "scheme", ")", "name", "=", "name", ".", "to_sym", "scheme", "=", "scheme", ".", "deep_dup", "@schemes", "[", "name", "]", "=", "IceNine", ".", "deep_freeze", "(", "scheme", ")", "@brahmic_schemes", ".", "add", "(", "name", ")", "@scheme_names", ".", "add", "(", "name", ")", "scheme", "end" ]
Add a Brahmic scheme to Sanscript. Schemes are of two types: "Brahmic" and "roman". Brahmic consonants have an inherent vowel sound, but roman consonants do not. This is the main difference between these two types of scheme. A scheme definition is a Hash that maps a group name to a list of characters. For illustration, see `transliterate/schemes.rb`. You can use whatever group names you like, but for the best results, you should use the same group names that Sanscript does. @param name [Symbol] the scheme name @param scheme [Hash] the scheme data, constructed as described above @return [Hash] the frozen scheme data as it exists inside the module
[ "Add", "a", "Brahmic", "scheme", "to", "Sanscript", "." ]
0e50c4a856599a7b13c9f0cbc281206245859c71
https://github.com/ubcsanskrit/sanscript.rb/blob/0e50c4a856599a7b13c9f0cbc281206245859c71/lib/sanscript/transliterate.rb#L74-L81
train
ubcsanskrit/sanscript.rb
lib/sanscript/transliterate.rb
Sanscript.Transliterate.add_roman_scheme
def add_roman_scheme(name, scheme) name = name.to_sym scheme = scheme.deep_dup scheme[:vowel_marks] = scheme[:vowels][1..-1] unless scheme.key?(:vowel_marks) @schemes[name] = IceNine.deep_freeze(scheme) @roman_schemes.add(name) @scheme_names.add(name) scheme end
ruby
def add_roman_scheme(name, scheme) name = name.to_sym scheme = scheme.deep_dup scheme[:vowel_marks] = scheme[:vowels][1..-1] unless scheme.key?(:vowel_marks) @schemes[name] = IceNine.deep_freeze(scheme) @roman_schemes.add(name) @scheme_names.add(name) scheme end
[ "def", "add_roman_scheme", "(", "name", ",", "scheme", ")", "name", "=", "name", ".", "to_sym", "scheme", "=", "scheme", ".", "deep_dup", "scheme", "[", ":vowel_marks", "]", "=", "scheme", "[", ":vowels", "]", "[", "1", "..", "-", "1", "]", "unless", "scheme", ".", "key?", "(", ":vowel_marks", ")", "@schemes", "[", "name", "]", "=", "IceNine", ".", "deep_freeze", "(", "scheme", ")", "@roman_schemes", ".", "add", "(", "name", ")", "@scheme_names", ".", "add", "(", "name", ")", "scheme", "end" ]
Add a roman scheme to Sanscript. @param name [Symbol] the scheme name @param scheme [Hash] the scheme data, constructed as in {add_brahmic_scheme}. The "vowel_marks" field can be omitted @return [Hash] the frozen scheme data as it exists inside the module
[ "Add", "a", "roman", "scheme", "to", "Sanscript", "." ]
0e50c4a856599a7b13c9f0cbc281206245859c71
https://github.com/ubcsanskrit/sanscript.rb/blob/0e50c4a856599a7b13c9f0cbc281206245859c71/lib/sanscript/transliterate.rb#L89-L97
train
ubcsanskrit/sanscript.rb
lib/sanscript/transliterate.rb
Sanscript.Transliterate.transliterate
def transliterate(data, from, to, **opts) from = from.to_sym to = to.to_sym return data if from == to raise SchemeNotSupportedError, from unless @schemes.key?(from) raise SchemeNotSupportedError, to unless @schemes.key?(to) data = data.to_str.dup options = @defaults.merge(opts) map = make_map(from, to) data.gsub!(/(<.*?>)/, "##\\1##") if options[:skip_sgml] # Easy way out for "{\m+}", "\", and ".h". if from == :itrans data.gsub!(/\{\\m\+\}/, ".h.N") data.gsub!(/\.h/, "") data.gsub!(/\\([^'`_]|$)/, "##\\1##") end if map[:from_roman?] transliterate_roman(data, map, options) else transliterate_brahmic(data, map) end end
ruby
def transliterate(data, from, to, **opts) from = from.to_sym to = to.to_sym return data if from == to raise SchemeNotSupportedError, from unless @schemes.key?(from) raise SchemeNotSupportedError, to unless @schemes.key?(to) data = data.to_str.dup options = @defaults.merge(opts) map = make_map(from, to) data.gsub!(/(<.*?>)/, "##\\1##") if options[:skip_sgml] # Easy way out for "{\m+}", "\", and ".h". if from == :itrans data.gsub!(/\{\\m\+\}/, ".h.N") data.gsub!(/\.h/, "") data.gsub!(/\\([^'`_]|$)/, "##\\1##") end if map[:from_roman?] transliterate_roman(data, map, options) else transliterate_brahmic(data, map) end end
[ "def", "transliterate", "(", "data", ",", "from", ",", "to", ",", "**", "opts", ")", "from", "=", "from", ".", "to_sym", "to", "=", "to", ".", "to_sym", "return", "data", "if", "from", "==", "to", "raise", "SchemeNotSupportedError", ",", "from", "unless", "@schemes", ".", "key?", "(", "from", ")", "raise", "SchemeNotSupportedError", ",", "to", "unless", "@schemes", ".", "key?", "(", "to", ")", "data", "=", "data", ".", "to_str", ".", "dup", "options", "=", "@defaults", ".", "merge", "(", "opts", ")", "map", "=", "make_map", "(", "from", ",", "to", ")", "data", ".", "gsub!", "(", "/", "/", ",", "\"##\\\\1##\"", ")", "if", "options", "[", ":skip_sgml", "]", "if", "from", "==", ":itrans", "data", ".", "gsub!", "(", "/", "\\{", "\\\\", "\\+", "\\}", "/", ",", "\".h.N\"", ")", "data", ".", "gsub!", "(", "/", "\\.", "/", ",", "\"\"", ")", "data", ".", "gsub!", "(", "/", "\\\\", "/", ",", "\"##\\\\1##\"", ")", "end", "if", "map", "[", ":from_roman?", "]", "transliterate_roman", "(", "data", ",", "map", ",", "options", ")", "else", "transliterate_brahmic", "(", "data", ",", "map", ")", "end", "end" ]
Transliterate from one script to another. @param data [String] the String to transliterate @param from [Symbol] the source script @param to [Symbol] the destination script @option opts [Boolean] :skip_sgml (false) escape SGML-style tags in text string @option opts [Boolean] :syncope (false) activate Hindi-style schwa syncope @return [String] the transliterated string
[ "Transliterate", "from", "one", "script", "to", "another", "." ]
0e50c4a856599a7b13c9f0cbc281206245859c71
https://github.com/ubcsanskrit/sanscript.rb/blob/0e50c4a856599a7b13c9f0cbc281206245859c71/lib/sanscript/transliterate.rb#L143-L168
train
postmodern/deployml
lib/deployml/local_shell.rb
DeploYML.LocalShell.run
def run(program,*arguments) program = program.to_s arguments = arguments.map { |arg| arg.to_s } system(program,*arguments) end
ruby
def run(program,*arguments) program = program.to_s arguments = arguments.map { |arg| arg.to_s } system(program,*arguments) end
[ "def", "run", "(", "program", ",", "*", "arguments", ")", "program", "=", "program", ".", "to_s", "arguments", "=", "arguments", ".", "map", "{", "|", "arg", "|", "arg", ".", "to_s", "}", "system", "(", "program", ",", "*", "arguments", ")", "end" ]
Runs a program locally. @param [String] program The name or path of the program to run. @param [Array<String>] arguments Additional arguments for the program.
[ "Runs", "a", "program", "locally", "." ]
4369d4ea719e41f0dc3aa6496e6422ad476b0dda
https://github.com/postmodern/deployml/blob/4369d4ea719e41f0dc3aa6496e6422ad476b0dda/lib/deployml/local_shell.rb#L18-L23
train
ryanstout/thor-ssh
lib/thor-ssh/remote_file.rb
ThorSsh.RemoteFile.mkdir_p
def mkdir_p(path) stdout, stderr, _, _ = exec("mkdir -p #{path.inspect}", :with_codes => true) if stderr =~ /Permission denied/ base.say_status :permission_error, stderr, :red raise PermissionError, "unable to create directory #{path}" end end
ruby
def mkdir_p(path) stdout, stderr, _, _ = exec("mkdir -p #{path.inspect}", :with_codes => true) if stderr =~ /Permission denied/ base.say_status :permission_error, stderr, :red raise PermissionError, "unable to create directory #{path}" end end
[ "def", "mkdir_p", "(", "path", ")", "stdout", ",", "stderr", ",", "_", ",", "_", "=", "exec", "(", "\"mkdir -p #{path.inspect}\"", ",", ":with_codes", "=>", "true", ")", "if", "stderr", "=~", "/", "/", "base", ".", "say_status", ":permission_error", ",", "stderr", ",", ":red", "raise", "PermissionError", ",", "\"unable to create directory #{path}\"", "end", "end" ]
Creates the directory at the path on the remote server
[ "Creates", "the", "directory", "at", "the", "path", "on", "the", "remote", "server" ]
fdfd4892ccf4fb40573d32f4331b7f0d1b6fe05d
https://github.com/ryanstout/thor-ssh/blob/fdfd4892ccf4fb40573d32f4331b7f0d1b6fe05d/lib/thor-ssh/remote_file.rb#L45-L52
train
ideonetwork/lato-core
lib/lato_core/cell.rb
LatoCore.Cell.validate_args
def validate_args(args: {}, requested_args: [], default_args: {}) requested_args.each do |requested_arg| raise "Cell must have #{requested_arg} argument" if args[requested_arg] == nil end default_args.each do |key, value| args[key] = value if args[key] == nil end args end
ruby
def validate_args(args: {}, requested_args: [], default_args: {}) requested_args.each do |requested_arg| raise "Cell must have #{requested_arg} argument" if args[requested_arg] == nil end default_args.each do |key, value| args[key] = value if args[key] == nil end args end
[ "def", "validate_args", "(", "args", ":", "{", "}", ",", "requested_args", ":", "[", "]", ",", "default_args", ":", "{", "}", ")", "requested_args", ".", "each", "do", "|", "requested_arg", "|", "raise", "\"Cell must have #{requested_arg} argument\"", "if", "args", "[", "requested_arg", "]", "==", "nil", "end", "default_args", ".", "each", "do", "|", "key", ",", "value", "|", "args", "[", "key", "]", "=", "value", "if", "args", "[", "key", "]", "==", "nil", "end", "args", "end" ]
This function is used from cells to validates arguments on constructor.
[ "This", "function", "is", "used", "from", "cells", "to", "validates", "arguments", "on", "constructor", "." ]
c01fa585725c8e9992f25d8a7bd4ba2d0bfca08c
https://github.com/ideonetwork/lato-core/blob/c01fa585725c8e9992f25d8a7bd4ba2d0bfca08c/lib/lato_core/cell.rb#L17-L27
train
razor-x/config_curator
lib/config_curator/utils.rb
ConfigCurator.Utils.command?
def command?(command) MakeMakefile::Logging.instance_variable_set :@logfile, File::NULL MakeMakefile::Logging.quiet = true MakeMakefile.find_executable command.to_s end
ruby
def command?(command) MakeMakefile::Logging.instance_variable_set :@logfile, File::NULL MakeMakefile::Logging.quiet = true MakeMakefile.find_executable command.to_s end
[ "def", "command?", "(", "command", ")", "MakeMakefile", "::", "Logging", ".", "instance_variable_set", ":@logfile", ",", "File", "::", "NULL", "MakeMakefile", "::", "Logging", ".", "quiet", "=", "true", "MakeMakefile", ".", "find_executable", "command", ".", "to_s", "end" ]
Checks if command exists. @param command [String] command name to check @return [String, nil] full path to command or nil if not found
[ "Checks", "if", "command", "exists", "." ]
b0c0742ba0c36acf66de3eafd23a7d17b210036b
https://github.com/razor-x/config_curator/blob/b0c0742ba0c36acf66de3eafd23a7d17b210036b/lib/config_curator/utils.rb#L9-L13
train
ianwhite/resources_controller
lib/resources_controller/specification.rb
ResourcesController.Specification.find_resource
def find_resource(controller) (controller.enclosing_resource ? controller.enclosing_resource.send(source) : klass).find controller.params[key] end
ruby
def find_resource(controller) (controller.enclosing_resource ? controller.enclosing_resource.send(source) : klass).find controller.params[key] end
[ "def", "find_resource", "(", "controller", ")", "(", "controller", ".", "enclosing_resource", "?", "controller", ".", "enclosing_resource", ".", "send", "(", "source", ")", ":", "klass", ")", ".", "find", "controller", ".", "params", "[", "key", "]", "end" ]
finds the resource on a controller using enclosing resources or resource class
[ "finds", "the", "resource", "on", "a", "controller", "using", "enclosing", "resources", "or", "resource", "class" ]
14e76843ccf7d22a6da5da6db81681397c4838c5
https://github.com/ianwhite/resources_controller/blob/14e76843ccf7d22a6da5da6db81681397c4838c5/lib/resources_controller/specification.rb#L77-L79
train
ianwhite/resources_controller
lib/resources_controller/specification.rb
ResourcesController.SingletonSpecification.find_resource
def find_resource(controller) ResourcesController.raise_cant_find_singleton(name, klass) unless controller.enclosing_resource controller.enclosing_resource.send(source) end
ruby
def find_resource(controller) ResourcesController.raise_cant_find_singleton(name, klass) unless controller.enclosing_resource controller.enclosing_resource.send(source) end
[ "def", "find_resource", "(", "controller", ")", "ResourcesController", ".", "raise_cant_find_singleton", "(", "name", ",", "klass", ")", "unless", "controller", ".", "enclosing_resource", "controller", ".", "enclosing_resource", ".", "send", "(", "source", ")", "end" ]
finds the resource from the enclosing resource. Raise CantFindSingleton if there is no enclosing resource
[ "finds", "the", "resource", "from", "the", "enclosing", "resource", ".", "Raise", "CantFindSingleton", "if", "there", "is", "no", "enclosing", "resource" ]
14e76843ccf7d22a6da5da6db81681397c4838c5
https://github.com/ianwhite/resources_controller/blob/14e76843ccf7d22a6da5da6db81681397c4838c5/lib/resources_controller/specification.rb#L114-L117
train
postmodern/deployml
lib/deployml/cli.rb
DeploYML.CLI.find_root
def find_root Pathname.pwd.ascend do |root| config_dir = root.join(Project::CONFIG_DIR) if config_dir.directory? config_file = config_dir.join(Project::CONFIG_FILE) return root if config_file.file? environments_dir = config_dir.join(Project::ENVIRONMENTS_DIR) return root if environments_dir.directory? end end shell.say "Could not find '#{Project::CONFIG_FILE}' in any parent directories", :red exit -1 end
ruby
def find_root Pathname.pwd.ascend do |root| config_dir = root.join(Project::CONFIG_DIR) if config_dir.directory? config_file = config_dir.join(Project::CONFIG_FILE) return root if config_file.file? environments_dir = config_dir.join(Project::ENVIRONMENTS_DIR) return root if environments_dir.directory? end end shell.say "Could not find '#{Project::CONFIG_FILE}' in any parent directories", :red exit -1 end
[ "def", "find_root", "Pathname", ".", "pwd", ".", "ascend", "do", "|", "root", "|", "config_dir", "=", "root", ".", "join", "(", "Project", "::", "CONFIG_DIR", ")", "if", "config_dir", ".", "directory?", "config_file", "=", "config_dir", ".", "join", "(", "Project", "::", "CONFIG_FILE", ")", "return", "root", "if", "config_file", ".", "file?", "environments_dir", "=", "config_dir", ".", "join", "(", "Project", "::", "ENVIRONMENTS_DIR", ")", "return", "root", "if", "environments_dir", ".", "directory?", "end", "end", "shell", ".", "say", "\"Could not find '#{Project::CONFIG_FILE}' in any parent directories\"", ",", ":red", "exit", "-", "1", "end" ]
Finds the root of the project, starting at the current working directory and ascending upwards. @return [Pathname] The root of the project. @since 0.3.0
[ "Finds", "the", "root", "of", "the", "project", "starting", "at", "the", "current", "working", "directory", "and", "ascending", "upwards", "." ]
4369d4ea719e41f0dc3aa6496e6422ad476b0dda
https://github.com/postmodern/deployml/blob/4369d4ea719e41f0dc3aa6496e6422ad476b0dda/lib/deployml/cli.rb#L229-L244
train
blahah/biopsy
lib/biopsy/objective_handler.rb
Biopsy.ObjectiveHandler.dimension_reduce
def dimension_reduce(results) # calculate the weighted Euclidean distance from optimal # d(p, q) = \sqrt{(p_1 - q_1)^2 + (p_2 - q_2)^2+...+(p_n - q_n)^2} # here the max value is sqrt(n) where n is no. of results, # min value (optimum) is 0 total = 0 results.each_value do |value| o = value[:optimum] w = value[:weighting] a = value[:result] m = value[:max] total += w * (((o - a) / m)**2) if m != 0 end Math.sqrt(total) / results.length end
ruby
def dimension_reduce(results) # calculate the weighted Euclidean distance from optimal # d(p, q) = \sqrt{(p_1 - q_1)^2 + (p_2 - q_2)^2+...+(p_n - q_n)^2} # here the max value is sqrt(n) where n is no. of results, # min value (optimum) is 0 total = 0 results.each_value do |value| o = value[:optimum] w = value[:weighting] a = value[:result] m = value[:max] total += w * (((o - a) / m)**2) if m != 0 end Math.sqrt(total) / results.length end
[ "def", "dimension_reduce", "(", "results", ")", "total", "=", "0", "results", ".", "each_value", "do", "|", "value", "|", "o", "=", "value", "[", ":optimum", "]", "w", "=", "value", "[", ":weighting", "]", "a", "=", "value", "[", ":result", "]", "m", "=", "value", "[", ":max", "]", "total", "+=", "w", "*", "(", "(", "(", "o", "-", "a", ")", "/", "m", ")", "**", "2", ")", "if", "m", "!=", "0", "end", "Math", ".", "sqrt", "(", "total", ")", "/", "results", ".", "length", "end" ]
Perform a euclidean distance dimension reduction of multiple objectives
[ "Perform", "a", "euclidean", "distance", "dimension", "reduction", "of", "multiple", "objectives" ]
e46f3d1c75de4da2ec47a377f7e4f0e16a8e03d2
https://github.com/blahah/biopsy/blob/e46f3d1c75de4da2ec47a377f7e4f0e16a8e03d2/lib/biopsy/objective_handler.rb#L99-L113
train
dwradcliffe/groupme
lib/groupme/bots.rb
GroupMe.Bots.bot_post
def bot_post(id, text, options = {}) data = { :bot_id => id, :text => text } data[:options] = options if options.any? post('/bots/post', data).status == 202 end
ruby
def bot_post(id, text, options = {}) data = { :bot_id => id, :text => text } data[:options] = options if options.any? post('/bots/post', data).status == 202 end
[ "def", "bot_post", "(", "id", ",", "text", ",", "options", "=", "{", "}", ")", "data", "=", "{", ":bot_id", "=>", "id", ",", ":text", "=>", "text", "}", "data", "[", ":options", "]", "=", "options", "if", "options", ".", "any?", "post", "(", "'/bots/post'", ",", "data", ")", ".", "status", "==", "202", "end" ]
Post a message from a bot. @return [Boolean] Success/Failure @see https://dev.groupme.com/docs/v3#bots_post @param id [String, Integer] ID of the bot @param text [String] Text to send to the group @option options [String] :picture_url Picture URL from image service
[ "Post", "a", "message", "from", "a", "bot", "." ]
a306dbcf38cc4d9ed219e010783799b2ccb4f9a2
https://github.com/dwradcliffe/groupme/blob/a306dbcf38cc4d9ed219e010783799b2ccb4f9a2/lib/groupme/bots.rb#L22-L29
train
dwradcliffe/groupme
lib/groupme/bots.rb
GroupMe.Bots.create_bot
def create_bot(name, group_id, options = {}) data = { :bot => options.merge(:name => name, :group_id => group_id) } post('/bots', data) end
ruby
def create_bot(name, group_id, options = {}) data = { :bot => options.merge(:name => name, :group_id => group_id) } post('/bots', data) end
[ "def", "create_bot", "(", "name", ",", "group_id", ",", "options", "=", "{", "}", ")", "data", "=", "{", ":bot", "=>", "options", ".", "merge", "(", ":name", "=>", "name", ",", ":group_id", "=>", "group_id", ")", "}", "post", "(", "'/bots'", ",", "data", ")", "end" ]
Create a new bot. @return [Hashie::Mash] Hash representing the bot. @see https://dev.groupme.com/docs/v3#bots_create @param name [String] Name for the new bot @param group_id [String, Integer] ID of the group @option options [String] :avatar_url Avatar image URL for the bot @option options [String] :callback_url Callback URL for the bot
[ "Create", "a", "new", "bot", "." ]
a306dbcf38cc4d9ed219e010783799b2ccb4f9a2
https://github.com/dwradcliffe/groupme/blob/a306dbcf38cc4d9ed219e010783799b2ccb4f9a2/lib/groupme/bots.rb#L39-L44
train
10Pines/aws_ses_newsletters
app/workers/aws_ses_newsletters/newsletters_sender.rb
AwsSesNewsletters.NewslettersSender.preview_to
def preview_to(recipient) @newsletter = build_newsletter mail = build_mail mail.to = recipient.email replace_and_send_mail_safely(mail, recipient) end
ruby
def preview_to(recipient) @newsletter = build_newsletter mail = build_mail mail.to = recipient.email replace_and_send_mail_safely(mail, recipient) end
[ "def", "preview_to", "(", "recipient", ")", "@newsletter", "=", "build_newsletter", "mail", "=", "build_mail", "mail", ".", "to", "=", "recipient", ".", "email", "replace_and_send_mail_safely", "(", "mail", ",", "recipient", ")", "end" ]
Send a preview email
[ "Send", "a", "preview", "email" ]
8c6d740ebad45d235e48b40bdb018cb25b1a28de
https://github.com/10Pines/aws_ses_newsletters/blob/8c6d740ebad45d235e48b40bdb018cb25b1a28de/app/workers/aws_ses_newsletters/newsletters_sender.rb#L21-L26
train
10Pines/aws_ses_newsletters
app/workers/aws_ses_newsletters/newsletters_sender.rb
AwsSesNewsletters.NewslettersSender.send_emails
def send_emails mail = build_mail get_recipients do |recipient| unless EmailResponse.exists?(email: recipient.email) # bounces & complaints mail.to = recipient.email replace_and_send_mail_safely(mail, recipient) end end end
ruby
def send_emails mail = build_mail get_recipients do |recipient| unless EmailResponse.exists?(email: recipient.email) # bounces & complaints mail.to = recipient.email replace_and_send_mail_safely(mail, recipient) end end end
[ "def", "send_emails", "mail", "=", "build_mail", "get_recipients", "do", "|", "recipient", "|", "unless", "EmailResponse", ".", "exists?", "(", "email", ":", "recipient", ".", "email", ")", "mail", ".", "to", "=", "recipient", ".", "email", "replace_and_send_mail_safely", "(", "mail", ",", "recipient", ")", "end", "end", "end" ]
Iterate over recipients and sends emails
[ "Iterate", "over", "recipients", "and", "sends", "emails" ]
8c6d740ebad45d235e48b40bdb018cb25b1a28de
https://github.com/10Pines/aws_ses_newsletters/blob/8c6d740ebad45d235e48b40bdb018cb25b1a28de/app/workers/aws_ses_newsletters/newsletters_sender.rb#L30-L38
train
10Pines/aws_ses_newsletters
app/workers/aws_ses_newsletters/newsletters_sender.rb
AwsSesNewsletters.NewslettersSender.replace_and_send_mail_safely
def replace_and_send_mail_safely(mail, recipient) html_body = mail.html_part.body.raw_source do_custom_replacements_for(mail, recipient) send_raw_email_safely(mail) mail.html_part.body = html_body end
ruby
def replace_and_send_mail_safely(mail, recipient) html_body = mail.html_part.body.raw_source do_custom_replacements_for(mail, recipient) send_raw_email_safely(mail) mail.html_part.body = html_body end
[ "def", "replace_and_send_mail_safely", "(", "mail", ",", "recipient", ")", "html_body", "=", "mail", ".", "html_part", ".", "body", ".", "raw_source", "do_custom_replacements_for", "(", "mail", ",", "recipient", ")", "send_raw_email_safely", "(", "mail", ")", "mail", ".", "html_part", ".", "body", "=", "html_body", "end" ]
Perform custom replacements and send the email without throwing any exception
[ "Perform", "custom", "replacements", "and", "send", "the", "email", "without", "throwing", "any", "exception" ]
8c6d740ebad45d235e48b40bdb018cb25b1a28de
https://github.com/10Pines/aws_ses_newsletters/blob/8c6d740ebad45d235e48b40bdb018cb25b1a28de/app/workers/aws_ses_newsletters/newsletters_sender.rb#L73-L78
train
10Pines/aws_ses_newsletters
app/workers/aws_ses_newsletters/newsletters_sender.rb
AwsSesNewsletters.NewslettersSender.build_mail
def build_mail AwsSesNewsletters::MailBuilder.new( from: newsletter.from, subject: newsletter.subject, html_body: newsletter.html_body, images: get_images, ).build end
ruby
def build_mail AwsSesNewsletters::MailBuilder.new( from: newsletter.from, subject: newsletter.subject, html_body: newsletter.html_body, images: get_images, ).build end
[ "def", "build_mail", "AwsSesNewsletters", "::", "MailBuilder", ".", "new", "(", "from", ":", "newsletter", ".", "from", ",", "subject", ":", "newsletter", ".", "subject", ",", "html_body", ":", "newsletter", ".", "html_body", ",", "images", ":", "get_images", ",", ")", ".", "build", "end" ]
Builds a Mail
[ "Builds", "a", "Mail" ]
8c6d740ebad45d235e48b40bdb018cb25b1a28de
https://github.com/10Pines/aws_ses_newsletters/blob/8c6d740ebad45d235e48b40bdb018cb25b1a28de/app/workers/aws_ses_newsletters/newsletters_sender.rb#L99-L106
train
wordjelly/Auth
app/models/auth/concerns/shopping/payment_concern.rb
Auth::Concerns::Shopping::PaymentConcern.ClassMethods.get_discount_payments
def get_discount_payments(cart_id) discount_payments = Auth.configuration.payment_class.constantize.where(:cart_id => cart_id, :discount_id.nin => ["", nil], :payment_status => 1) discount_payments end
ruby
def get_discount_payments(cart_id) discount_payments = Auth.configuration.payment_class.constantize.where(:cart_id => cart_id, :discount_id.nin => ["", nil], :payment_status => 1) discount_payments end
[ "def", "get_discount_payments", "(", "cart_id", ")", "discount_payments", "=", "Auth", ".", "configuration", ".", "payment_class", ".", "constantize", ".", "where", "(", ":cart_id", "=>", "cart_id", ",", ":discount_id", ".", "nin", "=>", "[", "\"\"", ",", "nil", "]", ",", ":payment_status", "=>", "1", ")", "discount_payments", "end" ]
will return discount_payments of this cart id with a payments_status of 1.
[ "will", "return", "discount_payments", "of", "this", "cart", "id", "with", "a", "payments_status", "of", "1", "." ]
e1b6697a13c845f57b3cc83bfb79059a09541f47
https://github.com/wordjelly/Auth/blob/e1b6697a13c845f57b3cc83bfb79059a09541f47/app/models/auth/concerns/shopping/payment_concern.rb#L208-L212
train
wordjelly/Auth
app/models/auth/concerns/shopping/payment_concern.rb
Auth::Concerns::Shopping::PaymentConcern.ClassMethods.get_sum_of_discount_payments
def get_sum_of_discount_payments(cart_id) sum_of_discount_payments = 0 get_discount_payments(cart_id).each do |dp| sum_of_discount_payments+= dp.amount end sum_of_discount_payments end
ruby
def get_sum_of_discount_payments(cart_id) sum_of_discount_payments = 0 get_discount_payments(cart_id).each do |dp| sum_of_discount_payments+= dp.amount end sum_of_discount_payments end
[ "def", "get_sum_of_discount_payments", "(", "cart_id", ")", "sum_of_discount_payments", "=", "0", "get_discount_payments", "(", "cart_id", ")", ".", "each", "do", "|", "dp", "|", "sum_of_discount_payments", "+=", "dp", ".", "amount", "end", "sum_of_discount_payments", "end" ]
will return the sum of the amounts of all successfull discount_payments.
[ "will", "return", "the", "sum", "of", "the", "amounts", "of", "all", "successfull", "discount_payments", "." ]
e1b6697a13c845f57b3cc83bfb79059a09541f47
https://github.com/wordjelly/Auth/blob/e1b6697a13c845f57b3cc83bfb79059a09541f47/app/models/auth/concerns/shopping/payment_concern.rb#L215-L224
train
ideonetwork/lato-core
lib/lato_core/interfaces/general.rb
LatoCore.Interface::General.core__read_yaml
def core__read_yaml(file_path) # return nil if file not exist return unless File.exist?(file_path) config_file = File.read(file_path) # return yaml data return YAML.safe_load(config_file).with_indifferent_access rescue nil end
ruby
def core__read_yaml(file_path) # return nil if file not exist return unless File.exist?(file_path) config_file = File.read(file_path) # return yaml data return YAML.safe_load(config_file).with_indifferent_access rescue nil end
[ "def", "core__read_yaml", "(", "file_path", ")", "return", "unless", "File", ".", "exist?", "(", "file_path", ")", "config_file", "=", "File", ".", "read", "(", "file_path", ")", "return", "YAML", ".", "safe_load", "(", "config_file", ")", ".", "with_indifferent_access", "rescue", "nil", "end" ]
This function takes a path to a yaml file and return the hash with yaml data or nil if file not exist.
[ "This", "function", "takes", "a", "path", "to", "a", "yaml", "file", "and", "return", "the", "hash", "with", "yaml", "data", "or", "nil", "if", "file", "not", "exist", "." ]
c01fa585725c8e9992f25d8a7bd4ba2d0bfca08c
https://github.com/ideonetwork/lato-core/blob/c01fa585725c8e9992f25d8a7bd4ba2d0bfca08c/lib/lato_core/interfaces/general.rb#L8-L16
train
ideonetwork/lato-core
lib/lato_core/interfaces/general.rb
LatoCore.Interface::General.core__paginate_array
def core__paginate_array(array, per_page, page) start = (page - 1) * per_page array[start, per_page] end
ruby
def core__paginate_array(array, per_page, page) start = (page - 1) * per_page array[start, per_page] end
[ "def", "core__paginate_array", "(", "array", ",", "per_page", ",", "page", ")", "start", "=", "(", "page", "-", "1", ")", "*", "per_page", "array", "[", "start", ",", "per_page", "]", "end" ]
This function paginate an array and return the requested page.
[ "This", "function", "paginate", "an", "array", "and", "return", "the", "requested", "page", "." ]
c01fa585725c8e9992f25d8a7bd4ba2d0bfca08c
https://github.com/ideonetwork/lato-core/blob/c01fa585725c8e9992f25d8a7bd4ba2d0bfca08c/lib/lato_core/interfaces/general.rb#L24-L27
train
ideonetwork/lato-core
lib/lato_core/interfaces/general.rb
LatoCore.Interface::General.core__add_param_to_url
def core__add_param_to_url(url, param_name, param_value) uri = URI(url) params = URI.decode_www_form(uri.query || "") << [param_name, param_value] uri.query = URI.encode_www_form(params) uri.to_s end
ruby
def core__add_param_to_url(url, param_name, param_value) uri = URI(url) params = URI.decode_www_form(uri.query || "") << [param_name, param_value] uri.query = URI.encode_www_form(params) uri.to_s end
[ "def", "core__add_param_to_url", "(", "url", ",", "param_name", ",", "param_value", ")", "uri", "=", "URI", "(", "url", ")", "params", "=", "URI", ".", "decode_www_form", "(", "uri", ".", "query", "||", "\"\"", ")", "<<", "[", "param_name", ",", "param_value", "]", "uri", ".", "query", "=", "URI", ".", "encode_www_form", "(", "params", ")", "uri", ".", "to_s", "end" ]
This function add a new GET param to an url string.
[ "This", "function", "add", "a", "new", "GET", "param", "to", "an", "url", "string", "." ]
c01fa585725c8e9992f25d8a7bd4ba2d0bfca08c
https://github.com/ideonetwork/lato-core/blob/c01fa585725c8e9992f25d8a7bd4ba2d0bfca08c/lib/lato_core/interfaces/general.rb#L30-L35
train
ManageIQ/polisher
lib/polisher/adaptors/checker_loader.rb
Polisher.CheckerLoader.targets
def targets @targets ||= Dir.glob(File.join(target_dir, '*.rb')) .collect { |t| t.gsub("#{target_dir}/", '').gsub('.rb', '').intern } end
ruby
def targets @targets ||= Dir.glob(File.join(target_dir, '*.rb')) .collect { |t| t.gsub("#{target_dir}/", '').gsub('.rb', '').intern } end
[ "def", "targets", "@targets", "||=", "Dir", ".", "glob", "(", "File", ".", "join", "(", "target_dir", ",", "'*.rb'", ")", ")", ".", "collect", "{", "|", "t", "|", "t", ".", "gsub", "(", "\"#{target_dir}/\"", ",", "''", ")", ".", "gsub", "(", "'.rb'", ",", "''", ")", ".", "intern", "}", "end" ]
Targets to check
[ "Targets", "to", "check" ]
8c19023c72573999c9dc53ec2e2a3eef11a9531e
https://github.com/ManageIQ/polisher/blob/8c19023c72573999c9dc53ec2e2a3eef11a9531e/lib/polisher/adaptors/checker_loader.rb#L17-L20
train
ManageIQ/polisher
lib/polisher/adaptors/checker_loader.rb
Polisher.CheckerLoader.load_target
def load_target(target) raise ArgumentError, target unless targets.include?(target) require "polisher/adaptors/version_checker/#{target}" tm = target_module(target) @target_modules ||= [] @target_modules << tm include tm end
ruby
def load_target(target) raise ArgumentError, target unless targets.include?(target) require "polisher/adaptors/version_checker/#{target}" tm = target_module(target) @target_modules ||= [] @target_modules << tm include tm end
[ "def", "load_target", "(", "target", ")", "raise", "ArgumentError", ",", "target", "unless", "targets", ".", "include?", "(", "target", ")", "require", "\"polisher/adaptors/version_checker/#{target}\"", "tm", "=", "target_module", "(", "target", ")", "@target_modules", "||=", "[", "]", "@target_modules", "<<", "tm", "include", "tm", "end" ]
Load specified target
[ "Load", "specified", "target" ]
8c19023c72573999c9dc53ec2e2a3eef11a9531e
https://github.com/ManageIQ/polisher/blob/8c19023c72573999c9dc53ec2e2a3eef11a9531e/lib/polisher/adaptors/checker_loader.rb#L38-L47
train
wordjelly/Auth
app/models/auth/concerns/activity_concern.rb
Auth::Concerns::ActivityConcern.ClassMethods.activities_from_to
def activities_from_to(query,default_from,default_to) defaults = {"range" => {"from" => default_from, "to" => default_to}} query = defaults.deep_merge(query) ##default from and to assigned here. from = query["range"]["from"].to_i to = query["range"]["to"].to_i if from >= to query["range"]["from"] = default_from query["range"]["to"] = default_to end return query end
ruby
def activities_from_to(query,default_from,default_to) defaults = {"range" => {"from" => default_from, "to" => default_to}} query = defaults.deep_merge(query) ##default from and to assigned here. from = query["range"]["from"].to_i to = query["range"]["to"].to_i if from >= to query["range"]["from"] = default_from query["range"]["to"] = default_to end return query end
[ "def", "activities_from_to", "(", "query", ",", "default_from", ",", "default_to", ")", "defaults", "=", "{", "\"range\"", "=>", "{", "\"from\"", "=>", "default_from", ",", "\"to\"", "=>", "default_to", "}", "}", "query", "=", "defaults", ".", "deep_merge", "(", "query", ")", "from", "=", "query", "[", "\"range\"", "]", "[", "\"from\"", "]", ".", "to_i", "to", "=", "query", "[", "\"range\"", "]", "[", "\"to\"", "]", ".", "to_i", "if", "from", ">=", "to", "query", "[", "\"range\"", "]", "[", "\"from\"", "]", "=", "default_from", "query", "[", "\"range\"", "]", "[", "\"to\"", "]", "=", "default_to", "end", "return", "query", "end" ]
the default "from" is the beginning of the current month, and the default "to" is the current time. @used_in : last_n_months, get_in_range @param[Hash] query: the "from","to" provided in the query if at all, otherwise nil, assumed that query has two keys : "from", "to", under a key called "range" @param[Integer] default_from : the default_from for the particular function that is firing this query, it is an epoch @param[Integer] default_to : the default_to for the particular function that is firing this query, it is an epoch @return[Hash] : default values for "from", "to"
[ "the", "default", "from", "is", "the", "beginning", "of", "the", "current", "month", "and", "the", "default", "to", "is", "the", "current", "time", "." ]
e1b6697a13c845f57b3cc83bfb79059a09541f47
https://github.com/wordjelly/Auth/blob/e1b6697a13c845f57b3cc83bfb79059a09541f47/app/models/auth/concerns/activity_concern.rb#L20-L31
train
wordjelly/Auth
app/models/auth/concerns/activity_concern.rb
Auth::Concerns::ActivityConcern.ClassMethods.activities_fields
def activities_fields(query) defaults = {"only" => Object.const_get(name).fields.keys} query = defaults.deep_merge(query) only = ((Object.const_get(name).fields.keys & query["only"]) + ["created_at"]) query["only"] = only return query end
ruby
def activities_fields(query) defaults = {"only" => Object.const_get(name).fields.keys} query = defaults.deep_merge(query) only = ((Object.const_get(name).fields.keys & query["only"]) + ["created_at"]) query["only"] = only return query end
[ "def", "activities_fields", "(", "query", ")", "defaults", "=", "{", "\"only\"", "=>", "Object", ".", "const_get", "(", "name", ")", ".", "fields", ".", "keys", "}", "query", "=", "defaults", ".", "deep_merge", "(", "query", ")", "only", "=", "(", "(", "Object", ".", "const_get", "(", "name", ")", ".", "fields", ".", "keys", "&", "query", "[", "\"only\"", "]", ")", "+", "[", "\"created_at\"", "]", ")", "query", "[", "\"only\"", "]", "=", "only", "return", "query", "end" ]
defaults for only. if it is empty or nil, then it becomes all attributes otherwise it becomes the intersect of all attributes and the ones specified in the only created_at had to be added here, because otherwise it throws an error saying missing_attribute in the only. I think this has something to do with the fact that it is used in the query, so it will be included in the result. @used_in: get_in_range @param[query] : the provided query, expected to be of the structure: {"only" => [array],,,other key value pairs} @return[Hash] query : returns the query with the default values for the fields to be returned
[ "defaults", "for", "only", ".", "if", "it", "is", "empty", "or", "nil", "then", "it", "becomes", "all", "attributes", "otherwise", "it", "becomes", "the", "intersect", "of", "all", "attributes", "and", "the", "ones", "specified", "in", "the", "only", "created_at", "had", "to", "be", "added", "here", "because", "otherwise", "it", "throws", "an", "error", "saying", "missing_attribute", "in", "the", "only", ".", "I", "think", "this", "has", "something", "to", "do", "with", "the", "fact", "that", "it", "is", "used", "in", "the", "query", "so", "it", "will", "be", "included", "in", "the", "result", "." ]
e1b6697a13c845f57b3cc83bfb79059a09541f47
https://github.com/wordjelly/Auth/blob/e1b6697a13c845f57b3cc83bfb79059a09541f47/app/models/auth/concerns/activity_concern.rb#L42-L48
train
logankoester/prometheus
lib/prometheus/extra/config/lib/plugin_dsl.rb
Prometheus.PluginDSL.start
def start if File.exists? CONFIG_PATH if Config.missing_configurables.size > 0 Prometheus::ConfigCommands.new.invoke :repair else super end else Prometheus::ConfigCommands.new.invoke :edit end end
ruby
def start if File.exists? CONFIG_PATH if Config.missing_configurables.size > 0 Prometheus::ConfigCommands.new.invoke :repair else super end else Prometheus::ConfigCommands.new.invoke :edit end end
[ "def", "start", "if", "File", ".", "exists?", "CONFIG_PATH", "if", "Config", ".", "missing_configurables", ".", "size", ">", "0", "Prometheus", "::", "ConfigCommands", ".", "new", ".", "invoke", ":repair", "else", "super", "end", "else", "Prometheus", "::", "ConfigCommands", ".", "new", ".", "invoke", ":edit", "end", "end" ]
Make sure the user has a complete config before continuing.
[ "Make", "sure", "the", "user", "has", "a", "complete", "config", "before", "continuing", "." ]
7ca710a69c7ab328b19c4d021539efc7ff93e6c0
https://github.com/logankoester/prometheus/blob/7ca710a69c7ab328b19c4d021539efc7ff93e6c0/lib/prometheus/extra/config/lib/plugin_dsl.rb#L4-L14
train
Sharparam/chatrix
lib/chatrix/users.rb
Chatrix.Users.[]
def [](id) return @users[id] if id.start_with? '@' res = @users.find { |_, u| u.displayname == id } res.last if res.respond_to? :last end
ruby
def [](id) return @users[id] if id.start_with? '@' res = @users.find { |_, u| u.displayname == id } res.last if res.respond_to? :last end
[ "def", "[]", "(", "id", ")", "return", "@users", "[", "id", "]", "if", "id", ".", "start_with?", "'@'", "res", "=", "@users", ".", "find", "{", "|", "_", ",", "u", "|", "u", ".", "displayname", "==", "id", "}", "res", ".", "last", "if", "res", ".", "respond_to?", ":last", "end" ]
Initializes a new Users instance. Gets a user by ID or display name. @param id [String] A user's ID or display name. @return [User,nil] The User instance for the specified user, or `nil` if the user could not be found.
[ "Initializes", "a", "new", "Users", "instance", ".", "Gets", "a", "user", "by", "ID", "or", "display", "name", "." ]
6f2e9cf3a614ba7e8a9960f7d9b97092c0ce1e34
https://github.com/Sharparam/chatrix/blob/6f2e9cf3a614ba7e8a9960f7d9b97092c0ce1e34/lib/chatrix/users.rb#L25-L30
train
Sharparam/chatrix
lib/chatrix/users.rb
Chatrix.Users.process_power_levels
def process_power_levels(room, data) data.each do |id, level| get_user(id).process_power_level room, level end end
ruby
def process_power_levels(room, data) data.each do |id, level| get_user(id).process_power_level room, level end end
[ "def", "process_power_levels", "(", "room", ",", "data", ")", "data", ".", "each", "do", "|", "id", ",", "level", "|", "get_user", "(", "id", ")", ".", "process_power_level", "room", ",", "level", "end", "end" ]
Process power level updates. @param room [Room] The room this event came from. @param data [Hash{String=>Fixnum}] Power level data, a hash of user IDs and their associated power level.
[ "Process", "power", "level", "updates", "." ]
6f2e9cf3a614ba7e8a9960f7d9b97092c0ce1e34
https://github.com/Sharparam/chatrix/blob/6f2e9cf3a614ba7e8a9960f7d9b97092c0ce1e34/lib/chatrix/users.rb#L47-L51
train
Sharparam/chatrix
lib/chatrix/users.rb
Chatrix.Users.process_invite
def process_invite(room, event) sender = get_user(event['sender']) invitee = get_user(event['state_key']) invitee.process_invite room, sender, event end
ruby
def process_invite(room, event) sender = get_user(event['sender']) invitee = get_user(event['state_key']) invitee.process_invite room, sender, event end
[ "def", "process_invite", "(", "room", ",", "event", ")", "sender", "=", "get_user", "(", "event", "[", "'sender'", "]", ")", "invitee", "=", "get_user", "(", "event", "[", "'state_key'", "]", ")", "invitee", ".", "process_invite", "room", ",", "sender", ",", "event", "end" ]
Process an invite event for a room. @param room [Room] The room from which the event originated. @param event [Hash] Event data.
[ "Process", "an", "invite", "event", "for", "a", "room", "." ]
6f2e9cf3a614ba7e8a9960f7d9b97092c0ce1e34
https://github.com/Sharparam/chatrix/blob/6f2e9cf3a614ba7e8a9960f7d9b97092c0ce1e34/lib/chatrix/users.rb#L57-L61
train
Sharparam/chatrix
lib/chatrix/users.rb
Chatrix.Users.get_user
def get_user(id) return @users[id] if @users.key? id user = User.new id @users[id] = user broadcast(:added, user) user end
ruby
def get_user(id) return @users[id] if @users.key? id user = User.new id @users[id] = user broadcast(:added, user) user end
[ "def", "get_user", "(", "id", ")", "return", "@users", "[", "id", "]", "if", "@users", ".", "key?", "id", "user", "=", "User", ".", "new", "id", "@users", "[", "id", "]", "=", "user", "broadcast", "(", ":added", ",", "user", ")", "user", "end" ]
Get the user instance for a specified user ID. If an instance does not exist for the user, one is created and returned. @param id [String] The user ID to get an instance for. @return [User] An instance of User for the specified ID.
[ "Get", "the", "user", "instance", "for", "a", "specified", "user", "ID", ".", "If", "an", "instance", "does", "not", "exist", "for", "the", "user", "one", "is", "created", "and", "returned", "." ]
6f2e9cf3a614ba7e8a9960f7d9b97092c0ce1e34
https://github.com/Sharparam/chatrix/blob/6f2e9cf3a614ba7e8a9960f7d9b97092c0ce1e34/lib/chatrix/users.rb#L70-L76
train
ianwhite/resources_controller
lib/resources_controller.rb
ResourcesController.ClassMethods.nested_in
def nested_in(*names, &block) options = names.extract_options! raise ArgumentError, "when giving more than one nesting, you may not specify options or a block" if names.length > 1 and (block_given? or options.length > 0) # convert :polymorphic option to '?' if options.delete(:polymorphic) raise ArgumentError, "when specifying :polymorphic => true, no block or other options may be given" if block_given? or options.length > 0 names = ["?#{names.first}"] end # ignore first '*' if it has already been specified by :load_enclosing == true names.shift if specifications == ['*'] && names.first == '*' names.each do |name| ensure_sane_wildcard if name == '*' specifications << (name.to_s =~ /^(\*|\?(.*))$/ ? name.to_s : Specification.new(name, options, &block)) end end
ruby
def nested_in(*names, &block) options = names.extract_options! raise ArgumentError, "when giving more than one nesting, you may not specify options or a block" if names.length > 1 and (block_given? or options.length > 0) # convert :polymorphic option to '?' if options.delete(:polymorphic) raise ArgumentError, "when specifying :polymorphic => true, no block or other options may be given" if block_given? or options.length > 0 names = ["?#{names.first}"] end # ignore first '*' if it has already been specified by :load_enclosing == true names.shift if specifications == ['*'] && names.first == '*' names.each do |name| ensure_sane_wildcard if name == '*' specifications << (name.to_s =~ /^(\*|\?(.*))$/ ? name.to_s : Specification.new(name, options, &block)) end end
[ "def", "nested_in", "(", "*", "names", ",", "&", "block", ")", "options", "=", "names", ".", "extract_options!", "raise", "ArgumentError", ",", "\"when giving more than one nesting, you may not specify options or a block\"", "if", "names", ".", "length", ">", "1", "and", "(", "block_given?", "or", "options", ".", "length", ">", "0", ")", "if", "options", ".", "delete", "(", ":polymorphic", ")", "raise", "ArgumentError", ",", "\"when specifying :polymorphic => true, no block or other options may be given\"", "if", "block_given?", "or", "options", ".", "length", ">", "0", "names", "=", "[", "\"?#{names.first}\"", "]", "end", "names", ".", "shift", "if", "specifications", "==", "[", "'*'", "]", "&&", "names", ".", "first", "==", "'*'", "names", ".", "each", "do", "|", "name", "|", "ensure_sane_wildcard", "if", "name", "==", "'*'", "specifications", "<<", "(", "name", ".", "to_s", "=~", "/", "\\*", "\\?", "/", "?", "name", ".", "to_s", ":", "Specification", ".", "new", "(", "name", ",", "options", ",", "&", "block", ")", ")", "end", "end" ]
Specifies that this controller has a particular enclosing resource. This can be called with an array of symbols (in which case options can't be specified) or a symbol with options. See Specification#new for details of how to call this.
[ "Specifies", "that", "this", "controller", "has", "a", "particular", "enclosing", "resource", "." ]
14e76843ccf7d22a6da5da6db81681397c4838c5
https://github.com/ianwhite/resources_controller/blob/14e76843ccf7d22a6da5da6db81681397c4838c5/lib/resources_controller.rb#L523-L540
train
ianwhite/resources_controller
lib/resources_controller.rb
ResourcesController.ClassMethods.ensure_sane_wildcard
def ensure_sane_wildcard idx = specifications.length while (idx -= 1) >= 0 if specifications[idx] == '*' raise ArgumentError, "Can only specify one wildcard '*' in between resource specifications" elsif specifications[idx].is_a?(Specification) break end end true end
ruby
def ensure_sane_wildcard idx = specifications.length while (idx -= 1) >= 0 if specifications[idx] == '*' raise ArgumentError, "Can only specify one wildcard '*' in between resource specifications" elsif specifications[idx].is_a?(Specification) break end end true end
[ "def", "ensure_sane_wildcard", "idx", "=", "specifications", ".", "length", "while", "(", "idx", "-=", "1", ")", ">=", "0", "if", "specifications", "[", "idx", "]", "==", "'*'", "raise", "ArgumentError", ",", "\"Can only specify one wildcard '*' in between resource specifications\"", "elsif", "specifications", "[", "idx", "]", ".", "is_a?", "(", "Specification", ")", "break", "end", "end", "true", "end" ]
ensure that specifications array is determinate w.r.t route matching
[ "ensure", "that", "specifications", "array", "is", "determinate", "w", ".", "r", ".", "t", "route", "matching" ]
14e76843ccf7d22a6da5da6db81681397c4838c5
https://github.com/ianwhite/resources_controller/blob/14e76843ccf7d22a6da5da6db81681397c4838c5/lib/resources_controller.rb#L544-L554
train
ianwhite/resources_controller
lib/resources_controller.rb
ResourcesController.InstanceMethods.load_enclosing_resources
def load_enclosing_resources namespace_segments.each {|segment| update_name_prefix("#{segment}_") } specifications.each_with_index do |spec, idx| case spec when '*' then load_wildcards_from(idx) when /^\?(.*)/ then load_wildcard($1) else load_enclosing_resource_from_specification(spec) end end end
ruby
def load_enclosing_resources namespace_segments.each {|segment| update_name_prefix("#{segment}_") } specifications.each_with_index do |spec, idx| case spec when '*' then load_wildcards_from(idx) when /^\?(.*)/ then load_wildcard($1) else load_enclosing_resource_from_specification(spec) end end end
[ "def", "load_enclosing_resources", "namespace_segments", ".", "each", "{", "|", "segment", "|", "update_name_prefix", "(", "\"#{segment}_\"", ")", "}", "specifications", ".", "each_with_index", "do", "|", "spec", ",", "idx", "|", "case", "spec", "when", "'*'", "then", "load_wildcards_from", "(", "idx", ")", "when", "/", "\\?", "/", "then", "load_wildcard", "(", "$1", ")", "else", "load_enclosing_resource_from_specification", "(", "spec", ")", "end", "end", "end" ]
this is the before_action that loads all specified and wildcard resources
[ "this", "is", "the", "before_action", "that", "loads", "all", "specified", "and", "wildcard", "resources" ]
14e76843ccf7d22a6da5da6db81681397c4838c5
https://github.com/ianwhite/resources_controller/blob/14e76843ccf7d22a6da5da6db81681397c4838c5/lib/resources_controller.rb#L662-L671
train
ianwhite/resources_controller
lib/resources_controller.rb
ResourcesController.InstanceMethods.load_wildcards_from
def load_wildcards_from(start) specs = specifications.slice(start..-1) encls = nesting_segments.slice(enclosing_resources.size..-1) if spec = specs.find {|s| s.is_a?(Specification)} spec_seg = encls.index({:segment => spec.segment, :singleton => spec.singleton?}) or ResourcesController.raise_resource_mismatch(self) number_of_wildcards = spec_seg - (specs.index(spec) -1) else number_of_wildcards = encls.length - (specs.length - 1) end number_of_wildcards.times { load_wildcard } end
ruby
def load_wildcards_from(start) specs = specifications.slice(start..-1) encls = nesting_segments.slice(enclosing_resources.size..-1) if spec = specs.find {|s| s.is_a?(Specification)} spec_seg = encls.index({:segment => spec.segment, :singleton => spec.singleton?}) or ResourcesController.raise_resource_mismatch(self) number_of_wildcards = spec_seg - (specs.index(spec) -1) else number_of_wildcards = encls.length - (specs.length - 1) end number_of_wildcards.times { load_wildcard } end
[ "def", "load_wildcards_from", "(", "start", ")", "specs", "=", "specifications", ".", "slice", "(", "start", "..", "-", "1", ")", "encls", "=", "nesting_segments", ".", "slice", "(", "enclosing_resources", ".", "size", "..", "-", "1", ")", "if", "spec", "=", "specs", ".", "find", "{", "|", "s", "|", "s", ".", "is_a?", "(", "Specification", ")", "}", "spec_seg", "=", "encls", ".", "index", "(", "{", ":segment", "=>", "spec", ".", "segment", ",", ":singleton", "=>", "spec", ".", "singleton?", "}", ")", "or", "ResourcesController", ".", "raise_resource_mismatch", "(", "self", ")", "number_of_wildcards", "=", "spec_seg", "-", "(", "specs", ".", "index", "(", "spec", ")", "-", "1", ")", "else", "number_of_wildcards", "=", "encls", ".", "length", "-", "(", "specs", ".", "length", "-", "1", ")", "end", "number_of_wildcards", ".", "times", "{", "load_wildcard", "}", "end" ]
loads a series of wildcard resources, from the specified specification idx To do this, we need to figure out where the next specified resource is and how many single wildcards are prior to that. What is left over from the current route enclosing names will be the number of wildcards we need to load
[ "loads", "a", "series", "of", "wildcard", "resources", "from", "the", "specified", "specification", "idx" ]
14e76843ccf7d22a6da5da6db81681397c4838c5
https://github.com/ianwhite/resources_controller/blob/14e76843ccf7d22a6da5da6db81681397c4838c5/lib/resources_controller.rb#L697-L709
train
ianwhite/resources_controller
lib/resources_controller.rb
ResourcesController.ResourceService.destroy
def destroy(*args) resource = find(*args) if enclosing_resource service.destroy(*args) resource else resource.destroy end end
ruby
def destroy(*args) resource = find(*args) if enclosing_resource service.destroy(*args) resource else resource.destroy end end
[ "def", "destroy", "(", "*", "args", ")", "resource", "=", "find", "(", "*", "args", ")", "if", "enclosing_resource", "service", ".", "destroy", "(", "*", "args", ")", "resource", "else", "resource", ".", "destroy", "end", "end" ]
find the resource If we have a resource service, we call destroy on it with the reosurce id, so that any callbacks can be triggered Otherwise, just call destroy on the resource
[ "find", "the", "resource", "If", "we", "have", "a", "resource", "service", "we", "call", "destroy", "on", "it", "with", "the", "reosurce", "id", "so", "that", "any", "callbacks", "can", "be", "triggered", "Otherwise", "just", "call", "destroy", "on", "the", "resource" ]
14e76843ccf7d22a6da5da6db81681397c4838c5
https://github.com/ianwhite/resources_controller/blob/14e76843ccf7d22a6da5da6db81681397c4838c5/lib/resources_controller.rb#L762-L770
train
ideonetwork/lato-core
app/models/lato_core/superuser/entity_helpers.rb
LatoCore.Superuser::EntityHelpers.get_permission_name
def get_permission_name permission = CONFIGS[:lato_core][:superusers_permissions].values.select{|x| x[:value] === self.permission} return permission[0][:title] if permission && !permission.empty? end
ruby
def get_permission_name permission = CONFIGS[:lato_core][:superusers_permissions].values.select{|x| x[:value] === self.permission} return permission[0][:title] if permission && !permission.empty? end
[ "def", "get_permission_name", "permission", "=", "CONFIGS", "[", ":lato_core", "]", "[", ":superusers_permissions", "]", ".", "values", ".", "select", "{", "|", "x", "|", "x", "[", ":value", "]", "===", "self", ".", "permission", "}", "return", "permission", "[", "0", "]", "[", ":title", "]", "if", "permission", "&&", "!", "permission", ".", "empty?", "end" ]
This function return the permission name for the user.
[ "This", "function", "return", "the", "permission", "name", "for", "the", "user", "." ]
c01fa585725c8e9992f25d8a7bd4ba2d0bfca08c
https://github.com/ideonetwork/lato-core/blob/c01fa585725c8e9992f25d8a7bd4ba2d0bfca08c/app/models/lato_core/superuser/entity_helpers.rb#L12-L15
train
Sharparam/chatrix
lib/chatrix/matrix.rb
Chatrix.Matrix.sync
def sync(filter: nil, since: nil, full_state: false, set_presence: true, timeout: 30_000) options = { full_state: full_state } options[:since] = since if since options[:set_presence] = 'offline' unless set_presence options[:timeout] = timeout if timeout options[:filter] = parse_filter filter make_request(:get, '/sync', params: options).parsed_response end
ruby
def sync(filter: nil, since: nil, full_state: false, set_presence: true, timeout: 30_000) options = { full_state: full_state } options[:since] = since if since options[:set_presence] = 'offline' unless set_presence options[:timeout] = timeout if timeout options[:filter] = parse_filter filter make_request(:get, '/sync', params: options).parsed_response end
[ "def", "sync", "(", "filter", ":", "nil", ",", "since", ":", "nil", ",", "full_state", ":", "false", ",", "set_presence", ":", "true", ",", "timeout", ":", "30_000", ")", "options", "=", "{", "full_state", ":", "full_state", "}", "options", "[", ":since", "]", "=", "since", "if", "since", "options", "[", ":set_presence", "]", "=", "'offline'", "unless", "set_presence", "options", "[", ":timeout", "]", "=", "timeout", "if", "timeout", "options", "[", ":filter", "]", "=", "parse_filter", "filter", "make_request", "(", ":get", ",", "'/sync'", ",", "params", ":", "options", ")", ".", "parsed_response", "end" ]
Synchronize with the latest state on the server. For initial sync, call this method with the `since` parameter set to `nil`. @param filter [String,Hash] The ID of a filter to use, or provided directly as a hash. @param since [String,nil] A point in time to continue sync from. Will retrieve a snapshot of the state if not set, which will also provide a `next_batch` value to use for `since` in the next call. @param full_state [Boolean] If `true`, all state events will be returned for all rooms the user is a member of. @param set_presence [Boolean] If `true`, the user performing this request will have their presence updated to show them as being online. @param timeout [Fixnum] Maximum time (in milliseconds) to wait before the request is aborted. @return [Hash] The initial snapshot of the state (if no `since` value was provided), or a delta to use for updating state.
[ "Synchronize", "with", "the", "latest", "state", "on", "the", "server", "." ]
6f2e9cf3a614ba7e8a9960f7d9b97092c0ce1e34
https://github.com/Sharparam/chatrix/blob/6f2e9cf3a614ba7e8a9960f7d9b97092c0ce1e34/lib/chatrix/matrix.rb#L134-L144
train
Sharparam/chatrix
lib/chatrix/matrix.rb
Chatrix.Matrix.search
def search(from: nil, options: {}) make_request( :post, '/search', params: { next_batch: from }, content: options ).parsed_response end
ruby
def search(from: nil, options: {}) make_request( :post, '/search', params: { next_batch: from }, content: options ).parsed_response end
[ "def", "search", "(", "from", ":", "nil", ",", "options", ":", "{", "}", ")", "make_request", "(", ":post", ",", "'/search'", ",", "params", ":", "{", "next_batch", ":", "from", "}", ",", "content", ":", "options", ")", ".", "parsed_response", "end" ]
Performs a full text search on the server. @param from [String] Where to return events from, if given. This can be obtained from previous calls to {#search}. @param options [Hash] Search options, see the official documentation for details on how to structure this. @return [Hash] the search results.
[ "Performs", "a", "full", "text", "search", "on", "the", "server", "." ]
6f2e9cf3a614ba7e8a9960f7d9b97092c0ce1e34
https://github.com/Sharparam/chatrix/blob/6f2e9cf3a614ba7e8a9960f7d9b97092c0ce1e34/lib/chatrix/matrix.rb#L168-L172
train
Sharparam/chatrix
lib/chatrix/matrix.rb
Chatrix.Matrix.make_request
def make_request(method, path, opts = {}, &block) path = (opts[:base] || @base_uri) + URI.encode(path) options = make_options opts[:params], opts[:content], opts[:headers] parse_response METHODS[method].call(path, options, &block) end
ruby
def make_request(method, path, opts = {}, &block) path = (opts[:base] || @base_uri) + URI.encode(path) options = make_options opts[:params], opts[:content], opts[:headers] parse_response METHODS[method].call(path, options, &block) end
[ "def", "make_request", "(", "method", ",", "path", ",", "opts", "=", "{", "}", ",", "&", "block", ")", "path", "=", "(", "opts", "[", ":base", "]", "||", "@base_uri", ")", "+", "URI", ".", "encode", "(", "path", ")", "options", "=", "make_options", "opts", "[", ":params", "]", ",", "opts", "[", ":content", "]", ",", "opts", "[", ":headers", "]", "parse_response", "METHODS", "[", "method", "]", ".", "call", "(", "path", ",", "options", ",", "&", "block", ")", "end" ]
Helper method for performing requests to the homeserver. @param method [Symbol] HTTP request method to use. Use only symbols available as keys in {METHODS}. @param path [String] The API path to query, relative to the base API path, eg. `/login`. @param opts [Hash] Additional request options. @option opts [Hash] :params Additional parameters to include in the query string (part of the URL, not put in the request body). @option opts [Hash,#read] :content Content to put in the request body. If set, must be a Hash or a stream object. @option opts [Hash{String => String}] :headers Additional headers to include in the request. @option opts [String,nil] :base If this is set, it will be used as the base URI for the request instead of the default (`@base_uri`). @yield [fragment] HTTParty will call the block during the request. @return [HTTParty::Response] The HTTParty response object.
[ "Helper", "method", "for", "performing", "requests", "to", "the", "homeserver", "." ]
6f2e9cf3a614ba7e8a9960f7d9b97092c0ce1e34
https://github.com/Sharparam/chatrix/blob/6f2e9cf3a614ba7e8a9960f7d9b97092c0ce1e34/lib/chatrix/matrix.rb#L201-L206
train
Sharparam/chatrix
lib/chatrix/matrix.rb
Chatrix.Matrix.make_options
def make_options(params, content, headers = {}) { headers: headers }.tap do |o| o[:query] = @access_token ? { access_token: @access_token } : {} o[:query].merge!(params) if params.is_a? Hash o.merge! make_body content end end
ruby
def make_options(params, content, headers = {}) { headers: headers }.tap do |o| o[:query] = @access_token ? { access_token: @access_token } : {} o[:query].merge!(params) if params.is_a? Hash o.merge! make_body content end end
[ "def", "make_options", "(", "params", ",", "content", ",", "headers", "=", "{", "}", ")", "{", "headers", ":", "headers", "}", ".", "tap", "do", "|", "o", "|", "o", "[", ":query", "]", "=", "@access_token", "?", "{", "access_token", ":", "@access_token", "}", ":", "{", "}", "o", "[", ":query", "]", ".", "merge!", "(", "params", ")", "if", "params", ".", "is_a?", "Hash", "o", ".", "merge!", "make_body", "content", "end", "end" ]
Create an options Hash to pass to a server request. This method embeds the {#access_token access_token} into the query parameters. @param params [Hash{String=>String},nil] Query parameters to add to the options hash. @param content [Hash,#read,nil] Request content. Can be a hash, stream, or `nil`. @return [Hash] Options hash ready to be passed into a server request.
[ "Create", "an", "options", "Hash", "to", "pass", "to", "a", "server", "request", "." ]
6f2e9cf3a614ba7e8a9960f7d9b97092c0ce1e34
https://github.com/Sharparam/chatrix/blob/6f2e9cf3a614ba7e8a9960f7d9b97092c0ce1e34/lib/chatrix/matrix.rb#L220-L226
train
Sharparam/chatrix
lib/chatrix/matrix.rb
Chatrix.Matrix.make_body
def make_body(content) key = content.respond_to?(:read) ? :body_stream : :body value = content.is_a?(Hash) ? content.to_json : content { key => value } end
ruby
def make_body(content) key = content.respond_to?(:read) ? :body_stream : :body value = content.is_a?(Hash) ? content.to_json : content { key => value } end
[ "def", "make_body", "(", "content", ")", "key", "=", "content", ".", "respond_to?", "(", ":read", ")", "?", ":body_stream", ":", ":body", "value", "=", "content", ".", "is_a?", "(", "Hash", ")", "?", "content", ".", "to_json", ":", "content", "{", "key", "=>", "value", "}", "end" ]
Create a hash with body content based on the type of `content`. @param content [Hash,#read,Object] Some kind of content to put into the request body. Can be a Hash, stream object, or other kind of object. @return [Hash{Symbol => Object}] A hash with the relevant body key and value.
[ "Create", "a", "hash", "with", "body", "content", "based", "on", "the", "type", "of", "content", "." ]
6f2e9cf3a614ba7e8a9960f7d9b97092c0ce1e34
https://github.com/Sharparam/chatrix/blob/6f2e9cf3a614ba7e8a9960f7d9b97092c0ce1e34/lib/chatrix/matrix.rb#L234-L238
train
Sharparam/chatrix
lib/chatrix/matrix.rb
Chatrix.Matrix.parse_response
def parse_response(response) case response.code when 200 # OK response else handler = ERROR_HANDLERS[response.code] raise handler.first.new(response.parsed_response), handler.last end end
ruby
def parse_response(response) case response.code when 200 # OK response else handler = ERROR_HANDLERS[response.code] raise handler.first.new(response.parsed_response), handler.last end end
[ "def", "parse_response", "(", "response", ")", "case", "response", ".", "code", "when", "200", "response", "else", "handler", "=", "ERROR_HANDLERS", "[", "response", ".", "code", "]", "raise", "handler", ".", "first", ".", "new", "(", "response", ".", "parsed_response", ")", ",", "handler", ".", "last", "end", "end" ]
Parses a HTTParty Response object and returns it if it was successful. @param response [HTTParty::Response] The response object to parse. @return [HTTParty::Response] The same response object that was passed in, if the request was successful. @raise [RequestError] If a `400` response code was returned from the request. @raise [AuthenticationError] If a `401` response code was returned from the request. @raise [ForbiddenError] If a `403` response code was returned from the request. @raise [NotFoundError] If a `404` response code was returned from the request. @raise [RateLimitError] If a `429` response code was returned from the request. @raise [ApiError] If an unknown response code was returned from the request.
[ "Parses", "a", "HTTParty", "Response", "object", "and", "returns", "it", "if", "it", "was", "successful", "." ]
6f2e9cf3a614ba7e8a9960f7d9b97092c0ce1e34
https://github.com/Sharparam/chatrix/blob/6f2e9cf3a614ba7e8a9960f7d9b97092c0ce1e34/lib/chatrix/matrix.rb#L258-L266
train
Sharparam/chatrix
lib/chatrix/matrix.rb
Chatrix.Matrix.parse_filter
def parse_filter(filter) filter.is_a?(Hash) ? URI.encode(filter.to_json) : filter end
ruby
def parse_filter(filter) filter.is_a?(Hash) ? URI.encode(filter.to_json) : filter end
[ "def", "parse_filter", "(", "filter", ")", "filter", ".", "is_a?", "(", "Hash", ")", "?", "URI", ".", "encode", "(", "filter", ".", "to_json", ")", ":", "filter", "end" ]
Parses a filter object for use in a query string. @param filter [String,Hash] The filter object to parse. @return [String] Query-friendly filter object. Or the `filter` parameter as-is if it failed to parse.
[ "Parses", "a", "filter", "object", "for", "use", "in", "a", "query", "string", "." ]
6f2e9cf3a614ba7e8a9960f7d9b97092c0ce1e34
https://github.com/Sharparam/chatrix/blob/6f2e9cf3a614ba7e8a9960f7d9b97092c0ce1e34/lib/chatrix/matrix.rb#L272-L274
train
picatz/command_lion
lib/command_lion/app.rb
CommandLion.App.command
def command(index, &block) if index.is_a? Command cmd = index else cmd = Command.new cmd.index= index cmd.instance_eval(&block) end @commands = {} unless @commands @flags = [] unless @flags if cmd.flags? @flags << cmd.flags.short if cmd.flags.short? @flags << cmd.flags.long if cmd.flags.long? elsif cmd.index # just use index @flags << cmd.index.to_s else raise "No index or flags were given to use this command." end if cmd.options? cmd.options.each do |_, option| if option.flags? @flags << option.flags.short if option.flags.short? @flags << option.flags.long if option.flags.long? else # just use index @flags << option.index.to_s end @commands[option.index] = option end end @commands[cmd.index] = cmd cmd end
ruby
def command(index, &block) if index.is_a? Command cmd = index else cmd = Command.new cmd.index= index cmd.instance_eval(&block) end @commands = {} unless @commands @flags = [] unless @flags if cmd.flags? @flags << cmd.flags.short if cmd.flags.short? @flags << cmd.flags.long if cmd.flags.long? elsif cmd.index # just use index @flags << cmd.index.to_s else raise "No index or flags were given to use this command." end if cmd.options? cmd.options.each do |_, option| if option.flags? @flags << option.flags.short if option.flags.short? @flags << option.flags.long if option.flags.long? else # just use index @flags << option.index.to_s end @commands[option.index] = option end end @commands[cmd.index] = cmd cmd end
[ "def", "command", "(", "index", ",", "&", "block", ")", "if", "index", ".", "is_a?", "Command", "cmd", "=", "index", "else", "cmd", "=", "Command", ".", "new", "cmd", ".", "index", "=", "index", "cmd", ".", "instance_eval", "(", "&", "block", ")", "end", "@commands", "=", "{", "}", "unless", "@commands", "@flags", "=", "[", "]", "unless", "@flags", "if", "cmd", ".", "flags?", "@flags", "<<", "cmd", ".", "flags", ".", "short", "if", "cmd", ".", "flags", ".", "short?", "@flags", "<<", "cmd", ".", "flags", ".", "long", "if", "cmd", ".", "flags", ".", "long?", "elsif", "cmd", ".", "index", "@flags", "<<", "cmd", ".", "index", ".", "to_s", "else", "raise", "\"No index or flags were given to use this command.\"", "end", "if", "cmd", ".", "options?", "cmd", ".", "options", ".", "each", "do", "|", "_", ",", "option", "|", "if", "option", ".", "flags?", "@flags", "<<", "option", ".", "flags", ".", "short", "if", "option", ".", "flags", ".", "short?", "@flags", "<<", "option", ".", "flags", ".", "long", "if", "option", ".", "flags", ".", "long?", "else", "@flags", "<<", "option", ".", "index", ".", "to_s", "end", "@commands", "[", "option", ".", "index", "]", "=", "option", "end", "end", "@commands", "[", "cmd", ".", "index", "]", "=", "cmd", "cmd", "end" ]
An application usually has multiple commands. == Example app = CommandLion::App.build # meta information command :example1 do # more code end command :example2 do # more code end end app.commands.map(&:name) # => [:example1, :example2]
[ "An", "application", "usually", "has", "multiple", "commands", "." ]
a101056a72c481e30a23c159e836e7b532c9b004
https://github.com/picatz/command_lion/blob/a101056a72c481e30a23c159e836e7b532c9b004/lib/command_lion/app.rb#L160-L191
train
picatz/command_lion
lib/command_lion/app.rb
CommandLion.App.parse
def parse @commands.each do |_, cmd| if cmd.flags? # or for the || seems to not do what I want it to do... next unless argv_index = ARGV.index(cmd.flags.short) || ARGV.index(cmd.flags.long) else next unless argv_index = ARGV.index(cmd.index.to_s) end cmd.given = true unless argv_index.nil? if cmd.type.nil? yield cmd if block_given? else if parsed = parse_cmd(cmd, flags) cmd.arguments = parsed || cmd.default yield cmd if block_given? elsif cmd.default cmd.arguments = cmd.default yield cmd if block_given? end end end end
ruby
def parse @commands.each do |_, cmd| if cmd.flags? # or for the || seems to not do what I want it to do... next unless argv_index = ARGV.index(cmd.flags.short) || ARGV.index(cmd.flags.long) else next unless argv_index = ARGV.index(cmd.index.to_s) end cmd.given = true unless argv_index.nil? if cmd.type.nil? yield cmd if block_given? else if parsed = parse_cmd(cmd, flags) cmd.arguments = parsed || cmd.default yield cmd if block_given? elsif cmd.default cmd.arguments = cmd.default yield cmd if block_given? end end end end
[ "def", "parse", "@commands", ".", "each", "do", "|", "_", ",", "cmd", "|", "if", "cmd", ".", "flags?", "next", "unless", "argv_index", "=", "ARGV", ".", "index", "(", "cmd", ".", "flags", ".", "short", ")", "||", "ARGV", ".", "index", "(", "cmd", ".", "flags", ".", "long", ")", "else", "next", "unless", "argv_index", "=", "ARGV", ".", "index", "(", "cmd", ".", "index", ".", "to_s", ")", "end", "cmd", ".", "given", "=", "true", "unless", "argv_index", ".", "nil?", "if", "cmd", ".", "type", ".", "nil?", "yield", "cmd", "if", "block_given?", "else", "if", "parsed", "=", "parse_cmd", "(", "cmd", ",", "flags", ")", "cmd", ".", "arguments", "=", "parsed", "||", "cmd", ".", "default", "yield", "cmd", "if", "block_given?", "elsif", "cmd", ".", "default", "cmd", ".", "arguments", "=", "cmd", ".", "default", "yield", "cmd", "if", "block_given?", "end", "end", "end", "end" ]
Parse arguments off of ARGV. @TODO Re-visit this.
[ "Parse", "arguments", "off", "of", "ARGV", "." ]
a101056a72c481e30a23c159e836e7b532c9b004
https://github.com/picatz/command_lion/blob/a101056a72c481e30a23c159e836e7b532c9b004/lib/command_lion/app.rb#L221-L242
train
picatz/command_lion
lib/command_lion/app.rb
CommandLion.App.parse_cmd
def parse_cmd(cmd, flags) if cmd.flags? args = Raw.arguments_to(cmd.flags.short, flags) if args.nil? || args.empty? args = Raw.arguments_to(cmd.flags.long, flags) end else args = Raw.arguments_to(cmd.index.to_s, flags) end unless cmd.type.to_s =~ /stdin/ return nil if args.nil? end case cmd.type when :stdin args = STDIN.gets.strip when :stdin_stream args = STDIN when :stdin_string args = STDIN.gets.strip when :stdin_strings args = [] while arg = STDIN.gets next if arg.nil? arg = arg.strip args << arg end args when :stdin_integer args = STDIN.gets.strip.to_i when :stdin_integers args = [] while arg = STDIN.gets next if arg.nil? arg = arg.strip parse = arg.to_i if parse.to_s == arg args << parse end end args when :stdin_bool args = STDIN.gets.strip.downcase == "true" when :single, :string args = args.first when :strings, :multi if cmd.delimiter? if args.count > 1 args = args.first.split(cmd.delimiter) else args = args.map { |arg| arg.split(cmd.delimiter) }.flatten end end args when :integer args = args.first.to_i when :integers if cmd.delimiter? if args.count > 1 args = args.join args = args.select { |arg| arg if arg.include?(cmd.delimiter) } args = args.map { |arg| arg.split(cmd.delimiter) }.flatten else args = args.map { |arg| arg.split(cmd.delimiter) }.flatten end end args = args.map(&:to_i) when :bool, :bools if cmd.delimiter? if args.count > 1 args = args.join args = args.select { |arg| arg if arg.include?(cmd.delimiter) } args = args.map { |arg| arg.split(cmd.delimiter) }.flatten else args = args.map { |arg| arg.split(cmd.delimiter) }.flatten end end args = args.map { |arg| arg == "true" } end rescue => e# this is dangerous puts e nil end
ruby
def parse_cmd(cmd, flags) if cmd.flags? args = Raw.arguments_to(cmd.flags.short, flags) if args.nil? || args.empty? args = Raw.arguments_to(cmd.flags.long, flags) end else args = Raw.arguments_to(cmd.index.to_s, flags) end unless cmd.type.to_s =~ /stdin/ return nil if args.nil? end case cmd.type when :stdin args = STDIN.gets.strip when :stdin_stream args = STDIN when :stdin_string args = STDIN.gets.strip when :stdin_strings args = [] while arg = STDIN.gets next if arg.nil? arg = arg.strip args << arg end args when :stdin_integer args = STDIN.gets.strip.to_i when :stdin_integers args = [] while arg = STDIN.gets next if arg.nil? arg = arg.strip parse = arg.to_i if parse.to_s == arg args << parse end end args when :stdin_bool args = STDIN.gets.strip.downcase == "true" when :single, :string args = args.first when :strings, :multi if cmd.delimiter? if args.count > 1 args = args.first.split(cmd.delimiter) else args = args.map { |arg| arg.split(cmd.delimiter) }.flatten end end args when :integer args = args.first.to_i when :integers if cmd.delimiter? if args.count > 1 args = args.join args = args.select { |arg| arg if arg.include?(cmd.delimiter) } args = args.map { |arg| arg.split(cmd.delimiter) }.flatten else args = args.map { |arg| arg.split(cmd.delimiter) }.flatten end end args = args.map(&:to_i) when :bool, :bools if cmd.delimiter? if args.count > 1 args = args.join args = args.select { |arg| arg if arg.include?(cmd.delimiter) } args = args.map { |arg| arg.split(cmd.delimiter) }.flatten else args = args.map { |arg| arg.split(cmd.delimiter) }.flatten end end args = args.map { |arg| arg == "true" } end rescue => e# this is dangerous puts e nil end
[ "def", "parse_cmd", "(", "cmd", ",", "flags", ")", "if", "cmd", ".", "flags?", "args", "=", "Raw", ".", "arguments_to", "(", "cmd", ".", "flags", ".", "short", ",", "flags", ")", "if", "args", ".", "nil?", "||", "args", ".", "empty?", "args", "=", "Raw", ".", "arguments_to", "(", "cmd", ".", "flags", ".", "long", ",", "flags", ")", "end", "else", "args", "=", "Raw", ".", "arguments_to", "(", "cmd", ".", "index", ".", "to_s", ",", "flags", ")", "end", "unless", "cmd", ".", "type", ".", "to_s", "=~", "/", "/", "return", "nil", "if", "args", ".", "nil?", "end", "case", "cmd", ".", "type", "when", ":stdin", "args", "=", "STDIN", ".", "gets", ".", "strip", "when", ":stdin_stream", "args", "=", "STDIN", "when", ":stdin_string", "args", "=", "STDIN", ".", "gets", ".", "strip", "when", ":stdin_strings", "args", "=", "[", "]", "while", "arg", "=", "STDIN", ".", "gets", "next", "if", "arg", ".", "nil?", "arg", "=", "arg", ".", "strip", "args", "<<", "arg", "end", "args", "when", ":stdin_integer", "args", "=", "STDIN", ".", "gets", ".", "strip", ".", "to_i", "when", ":stdin_integers", "args", "=", "[", "]", "while", "arg", "=", "STDIN", ".", "gets", "next", "if", "arg", ".", "nil?", "arg", "=", "arg", ".", "strip", "parse", "=", "arg", ".", "to_i", "if", "parse", ".", "to_s", "==", "arg", "args", "<<", "parse", "end", "end", "args", "when", ":stdin_bool", "args", "=", "STDIN", ".", "gets", ".", "strip", ".", "downcase", "==", "\"true\"", "when", ":single", ",", ":string", "args", "=", "args", ".", "first", "when", ":strings", ",", ":multi", "if", "cmd", ".", "delimiter?", "if", "args", ".", "count", ">", "1", "args", "=", "args", ".", "first", ".", "split", "(", "cmd", ".", "delimiter", ")", "else", "args", "=", "args", ".", "map", "{", "|", "arg", "|", "arg", ".", "split", "(", "cmd", ".", "delimiter", ")", "}", ".", "flatten", "end", "end", "args", "when", ":integer", "args", "=", "args", ".", "first", ".", "to_i", "when", ":integers", "if", "cmd", ".", "delimiter?", "if", "args", ".", "count", ">", "1", "args", "=", "args", ".", "join", "args", "=", "args", ".", "select", "{", "|", "arg", "|", "arg", "if", "arg", ".", "include?", "(", "cmd", ".", "delimiter", ")", "}", "args", "=", "args", ".", "map", "{", "|", "arg", "|", "arg", ".", "split", "(", "cmd", ".", "delimiter", ")", "}", ".", "flatten", "else", "args", "=", "args", ".", "map", "{", "|", "arg", "|", "arg", ".", "split", "(", "cmd", ".", "delimiter", ")", "}", ".", "flatten", "end", "end", "args", "=", "args", ".", "map", "(", "&", ":to_i", ")", "when", ":bool", ",", ":bools", "if", "cmd", ".", "delimiter?", "if", "args", ".", "count", ">", "1", "args", "=", "args", ".", "join", "args", "=", "args", ".", "select", "{", "|", "arg", "|", "arg", "if", "arg", ".", "include?", "(", "cmd", ".", "delimiter", ")", "}", "args", "=", "args", ".", "map", "{", "|", "arg", "|", "arg", ".", "split", "(", "cmd", ".", "delimiter", ")", "}", ".", "flatten", "else", "args", "=", "args", ".", "map", "{", "|", "arg", "|", "arg", ".", "split", "(", "cmd", ".", "delimiter", ")", "}", ".", "flatten", "end", "end", "args", "=", "args", ".", "map", "{", "|", "arg", "|", "arg", "==", "\"true\"", "}", "end", "rescue", "=>", "e", "puts", "e", "nil", "end" ]
Parse a given command with its given flags. @TODO Re-visit this.
[ "Parse", "a", "given", "command", "with", "its", "given", "flags", "." ]
a101056a72c481e30a23c159e836e7b532c9b004
https://github.com/picatz/command_lion/blob/a101056a72c481e30a23c159e836e7b532c9b004/lib/command_lion/app.rb#L246-L327
train
thinkerbot/configurable
lib/configurable/config_hash.rb
Configurable.ConfigHash.[]=
def []=(key, value) if config = configs[key] config.set(receiver, value) else store[key] = value end end
ruby
def []=(key, value) if config = configs[key] config.set(receiver, value) else store[key] = value end end
[ "def", "[]=", "(", "key", ",", "value", ")", "if", "config", "=", "configs", "[", "key", "]", "config", ".", "set", "(", "receiver", ",", "value", ")", "else", "store", "[", "key", "]", "=", "value", "end", "end" ]
Stores a value for the key, either on the receiver or in the store.
[ "Stores", "a", "value", "for", "the", "key", "either", "on", "the", "receiver", "or", "in", "the", "store", "." ]
43c611f767f14194827b1fe31bc72c8bdf54efdf
https://github.com/thinkerbot/configurable/blob/43c611f767f14194827b1fe31bc72c8bdf54efdf/lib/configurable/config_hash.rb#L82-L88
train
thinkerbot/configurable
lib/configurable/config_hash.rb
Configurable.ConfigHash.merge!
def merge!(another) configs = self.configs another.each_pair do |key, value| if config = configs[key] config.set(receiver, value) else store[key] = value end end self end
ruby
def merge!(another) configs = self.configs another.each_pair do |key, value| if config = configs[key] config.set(receiver, value) else store[key] = value end end self end
[ "def", "merge!", "(", "another", ")", "configs", "=", "self", ".", "configs", "another", ".", "each_pair", "do", "|", "key", ",", "value", "|", "if", "config", "=", "configs", "[", "key", "]", "config", ".", "set", "(", "receiver", ",", "value", ")", "else", "store", "[", "key", "]", "=", "value", "end", "end", "self", "end" ]
Merges another with self.
[ "Merges", "another", "with", "self", "." ]
43c611f767f14194827b1fe31bc72c8bdf54efdf
https://github.com/thinkerbot/configurable/blob/43c611f767f14194827b1fe31bc72c8bdf54efdf/lib/configurable/config_hash.rb#L101-L111
train
thinkerbot/configurable
lib/configurable/config_hash.rb
Configurable.ConfigHash.each_pair
def each_pair # :yields: key, value configs.each_pair do |key, config| yield(key, config.get(receiver)) end store.each_pair do |key, value| yield(key, value) end end
ruby
def each_pair # :yields: key, value configs.each_pair do |key, config| yield(key, config.get(receiver)) end store.each_pair do |key, value| yield(key, value) end end
[ "def", "each_pair", "configs", ".", "each_pair", "do", "|", "key", ",", "config", "|", "yield", "(", "key", ",", "config", ".", "get", "(", "receiver", ")", ")", "end", "store", ".", "each_pair", "do", "|", "key", ",", "value", "|", "yield", "(", "key", ",", "value", ")", "end", "end" ]
Calls block once for each key-value pair stored in self.
[ "Calls", "block", "once", "for", "each", "key", "-", "value", "pair", "stored", "in", "self", "." ]
43c611f767f14194827b1fe31bc72c8bdf54efdf
https://github.com/thinkerbot/configurable/blob/43c611f767f14194827b1fe31bc72c8bdf54efdf/lib/configurable/config_hash.rb#L114-L122
train
thinkerbot/configurable
lib/configurable/config_hash.rb
Configurable.ConfigHash.to_hash
def to_hash hash = {} each_pair do |key, value| if value.kind_of?(ConfigHash) value = value.to_hash end hash[key] = value end hash end
ruby
def to_hash hash = {} each_pair do |key, value| if value.kind_of?(ConfigHash) value = value.to_hash end hash[key] = value end hash end
[ "def", "to_hash", "hash", "=", "{", "}", "each_pair", "do", "|", "key", ",", "value", "|", "if", "value", ".", "kind_of?", "(", "ConfigHash", ")", "value", "=", "value", ".", "to_hash", "end", "hash", "[", "key", "]", "=", "value", "end", "hash", "end" ]
Equal if the to_hash values of self and another are equal. Returns self as a hash. Any ConfigHash values are recursively hashified, to account for nesting.
[ "Equal", "if", "the", "to_hash", "values", "of", "self", "and", "another", "are", "equal", ".", "Returns", "self", "as", "a", "hash", ".", "Any", "ConfigHash", "values", "are", "recursively", "hashified", "to", "account", "for", "nesting", "." ]
43c611f767f14194827b1fe31bc72c8bdf54efdf
https://github.com/thinkerbot/configurable/blob/43c611f767f14194827b1fe31bc72c8bdf54efdf/lib/configurable/config_hash.rb#L131-L141
train
scepticulous/crypto-toolbox
lib/crypto-toolbox/ciphers/aes.rb
Ciphers.Aes.decipher_ecb
def decipher_ecb(key,input,strip_padding: true) plain = decipher_ecb_blockwise(CryptBuffer(key),CryptBuffer(input).chunks_of(@block_size_bytes)).to_crypt_buffer strip_padding ? plain.strip_padding : plain end
ruby
def decipher_ecb(key,input,strip_padding: true) plain = decipher_ecb_blockwise(CryptBuffer(key),CryptBuffer(input).chunks_of(@block_size_bytes)).to_crypt_buffer strip_padding ? plain.strip_padding : plain end
[ "def", "decipher_ecb", "(", "key", ",", "input", ",", "strip_padding", ":", "true", ")", "plain", "=", "decipher_ecb_blockwise", "(", "CryptBuffer", "(", "key", ")", ",", "CryptBuffer", "(", "input", ")", ".", "chunks_of", "(", "@block_size_bytes", ")", ")", ".", "to_crypt_buffer", "strip_padding", "?", "plain", ".", "strip_padding", ":", "plain", "end" ]
NOTE convert ECB encryption to AES gem or both to openssl
[ "NOTE", "convert", "ECB", "encryption", "to", "AES", "gem", "or", "both", "to", "openssl" ]
cdbe371109e497db2c2af5c1fe0f359612f44816
https://github.com/scepticulous/crypto-toolbox/blob/cdbe371109e497db2c2af5c1fe0f359612f44816/lib/crypto-toolbox/ciphers/aes.rb#L12-L15
train
scepticulous/crypto-toolbox
lib/crypto-toolbox/ciphers/aes.rb
Ciphers.Aes.unicipher_cbc
def unicipher_cbc(direction,key_str,input_buf,iv) method="#{direction.to_s}_cbc_block" blocks = input_buf.chunks_of(@block_size_bytes) iv ||= blocks.shift.str key = CryptBuffer(key_str).hex prev_block=iv.to_crypt_buffer strings = blocks.map.with_index do |block,i| ctext_block = send(method,key,block,prev_block) if direction == :encipher prev_block = ctext_block else prev_block = block end ctext_block.str end CryptBuffer(strings.join) end
ruby
def unicipher_cbc(direction,key_str,input_buf,iv) method="#{direction.to_s}_cbc_block" blocks = input_buf.chunks_of(@block_size_bytes) iv ||= blocks.shift.str key = CryptBuffer(key_str).hex prev_block=iv.to_crypt_buffer strings = blocks.map.with_index do |block,i| ctext_block = send(method,key,block,prev_block) if direction == :encipher prev_block = ctext_block else prev_block = block end ctext_block.str end CryptBuffer(strings.join) end
[ "def", "unicipher_cbc", "(", "direction", ",", "key_str", ",", "input_buf", ",", "iv", ")", "method", "=", "\"#{direction.to_s}_cbc_block\"", "blocks", "=", "input_buf", ".", "chunks_of", "(", "@block_size_bytes", ")", "iv", "||=", "blocks", ".", "shift", ".", "str", "key", "=", "CryptBuffer", "(", "key_str", ")", ".", "hex", "prev_block", "=", "iv", ".", "to_crypt_buffer", "strings", "=", "blocks", ".", "map", ".", "with_index", "do", "|", "block", ",", "i", "|", "ctext_block", "=", "send", "(", "method", ",", "key", ",", "block", ",", "prev_block", ")", "if", "direction", "==", ":encipher", "prev_block", "=", "ctext_block", "else", "prev_block", "=", "block", "end", "ctext_block", ".", "str", "end", "CryptBuffer", "(", "strings", ".", "join", ")", "end" ]
this method is used for encipher and decipher since most of the code is identical only the value of the previous block and the internal ecb method differs
[ "this", "method", "is", "used", "for", "encipher", "and", "decipher", "since", "most", "of", "the", "code", "is", "identical", "only", "the", "value", "of", "the", "previous", "block", "and", "the", "internal", "ecb", "method", "differs" ]
cdbe371109e497db2c2af5c1fe0f359612f44816
https://github.com/scepticulous/crypto-toolbox/blob/cdbe371109e497db2c2af5c1fe0f359612f44816/lib/crypto-toolbox/ciphers/aes.rb#L68-L89
train
Birdie0/qna_maker
lib/qna_maker/endpoints/generate_answer.rb
QnAMaker.Client.generate_answer
def generate_answer(question, top = 1) response = @http.post( "#{BASE_URL}/#{@knowledgebase_id}/generateAnswer", json: { question: question, top: top } ) case response.code when 200 response.parse['answers'].map do |answer| Answer.new( answer['answer'].normalize, answer['questions'].map(&:normalize), answer['score'] ) end when 400 raise BadArgumentError, response.parse['error']['message'].join(' ') when 401 raise UnauthorizedError, response.parse['error']['message'] when 403 raise QuotaExceededError, response.parse['error']['message'] when 404 raise NotFoundError, response.parse['error']['message'] when 408 raise OperationTimeOutError, response.parse['error']['message'] when 429 raise RateLimitExceededError, response.parse['error']['message'] else raise UnknownError, "Oh no! (#{response.code})" end end
ruby
def generate_answer(question, top = 1) response = @http.post( "#{BASE_URL}/#{@knowledgebase_id}/generateAnswer", json: { question: question, top: top } ) case response.code when 200 response.parse['answers'].map do |answer| Answer.new( answer['answer'].normalize, answer['questions'].map(&:normalize), answer['score'] ) end when 400 raise BadArgumentError, response.parse['error']['message'].join(' ') when 401 raise UnauthorizedError, response.parse['error']['message'] when 403 raise QuotaExceededError, response.parse['error']['message'] when 404 raise NotFoundError, response.parse['error']['message'] when 408 raise OperationTimeOutError, response.parse['error']['message'] when 429 raise RateLimitExceededError, response.parse['error']['message'] else raise UnknownError, "Oh no! (#{response.code})" end end
[ "def", "generate_answer", "(", "question", ",", "top", "=", "1", ")", "response", "=", "@http", ".", "post", "(", "\"#{BASE_URL}/#{@knowledgebase_id}/generateAnswer\"", ",", "json", ":", "{", "question", ":", "question", ",", "top", ":", "top", "}", ")", "case", "response", ".", "code", "when", "200", "response", ".", "parse", "[", "'answers'", "]", ".", "map", "do", "|", "answer", "|", "Answer", ".", "new", "(", "answer", "[", "'answer'", "]", ".", "normalize", ",", "answer", "[", "'questions'", "]", ".", "map", "(", "&", ":normalize", ")", ",", "answer", "[", "'score'", "]", ")", "end", "when", "400", "raise", "BadArgumentError", ",", "response", ".", "parse", "[", "'error'", "]", "[", "'message'", "]", ".", "join", "(", "' '", ")", "when", "401", "raise", "UnauthorizedError", ",", "response", ".", "parse", "[", "'error'", "]", "[", "'message'", "]", "when", "403", "raise", "QuotaExceededError", ",", "response", ".", "parse", "[", "'error'", "]", "[", "'message'", "]", "when", "404", "raise", "NotFoundError", ",", "response", ".", "parse", "[", "'error'", "]", "[", "'message'", "]", "when", "408", "raise", "OperationTimeOutError", ",", "response", ".", "parse", "[", "'error'", "]", "[", "'message'", "]", "when", "429", "raise", "RateLimitExceededError", ",", "response", ".", "parse", "[", "'error'", "]", "[", "'message'", "]", "else", "raise", "UnknownError", ",", "\"Oh no! (#{response.code})\"", "end", "end" ]
Returns the list of answers for the given question sorted in descending order of ranking score. @param [String] question user question to be queried against your knowledge base. @param [Integer] top number of ranked results you want in the output. @return [Array<Answer>] list of answers for the user query sorted in decreasing order of ranking score.
[ "Returns", "the", "list", "of", "answers", "for", "the", "given", "question", "sorted", "in", "descending", "order", "of", "ranking", "score", "." ]
5ac204ede100355352438b8ff4fe30ad84d9257b
https://github.com/Birdie0/qna_maker/blob/5ac204ede100355352438b8ff4fe30ad84d9257b/lib/qna_maker/endpoints/generate_answer.rb#L14-L44
train
ideonetwork/lato-core
lib/lato_core/helpers/cells.rb
LatoCore.Helper::Cells.cell
def cell(*names) # define variables names_list = names.first.to_s.start_with?('Lato') ? names[1..-1] : names cell_class = names.first.to_s.start_with?('Lato') ? "#{names.first}::" : 'LatoCore::' # return correct cell names_list.each do |name| cell_class = "#{cell_class}#{name.capitalize}::" end "#{cell_class}Cell".constantize end
ruby
def cell(*names) # define variables names_list = names.first.to_s.start_with?('Lato') ? names[1..-1] : names cell_class = names.first.to_s.start_with?('Lato') ? "#{names.first}::" : 'LatoCore::' # return correct cell names_list.each do |name| cell_class = "#{cell_class}#{name.capitalize}::" end "#{cell_class}Cell".constantize end
[ "def", "cell", "(", "*", "names", ")", "names_list", "=", "names", ".", "first", ".", "to_s", ".", "start_with?", "(", "'Lato'", ")", "?", "names", "[", "1", "..", "-", "1", "]", ":", "names", "cell_class", "=", "names", ".", "first", ".", "to_s", ".", "start_with?", "(", "'Lato'", ")", "?", "\"#{names.first}::\"", ":", "'LatoCore::'", "names_list", ".", "each", "do", "|", "name", "|", "cell_class", "=", "\"#{cell_class}#{name.capitalize}::\"", "end", "\"#{cell_class}Cell\"", ".", "constantize", "end" ]
This helper is used to create a new cell with a pretty format.
[ "This", "helper", "is", "used", "to", "create", "a", "new", "cell", "with", "a", "pretty", "format", "." ]
c01fa585725c8e9992f25d8a7bd4ba2d0bfca08c
https://github.com/ideonetwork/lato-core/blob/c01fa585725c8e9992f25d8a7bd4ba2d0bfca08c/lib/lato_core/helpers/cells.rb#L7-L16
train
sergey-koba-mobidev/boxroom-engine
app/controllers/boxroom/folders_controller.rb
Boxroom.FoldersController.require_delete_permission
def require_delete_permission unless @folder.is_root? || boxroom_current_user.can_delete(@folder) redirect_to @folder.parent, :alert => t(:no_permissions_for_this_type, :method => t(:delete), :type => t(:this_folder)) else require_delete_permissions_for(@folder.children) end end
ruby
def require_delete_permission unless @folder.is_root? || boxroom_current_user.can_delete(@folder) redirect_to @folder.parent, :alert => t(:no_permissions_for_this_type, :method => t(:delete), :type => t(:this_folder)) else require_delete_permissions_for(@folder.children) end end
[ "def", "require_delete_permission", "unless", "@folder", ".", "is_root?", "||", "boxroom_current_user", ".", "can_delete", "(", "@folder", ")", "redirect_to", "@folder", ".", "parent", ",", ":alert", "=>", "t", "(", ":no_permissions_for_this_type", ",", ":method", "=>", "t", "(", ":delete", ")", ",", ":type", "=>", "t", "(", ":this_folder", ")", ")", "else", "require_delete_permissions_for", "(", "@folder", ".", "children", ")", "end", "end" ]
Overrides require_delete_permission in ApplicationController
[ "Overrides", "require_delete_permission", "in", "ApplicationController" ]
ce7a6b3fc6a1e5c36021429c0d337fab71993427
https://github.com/sergey-koba-mobidev/boxroom-engine/blob/ce7a6b3fc6a1e5c36021429c0d337fab71993427/app/controllers/boxroom/folders_controller.rb#L76-L82
train
dolzenko/reflexive
lib/reflexive/routing_helpers.rb
Reflexive.RoutingHelpers.method_call_path
def method_call_path(method_call_tag) # r method_call_tag.values_at(:name, :receiver) name, receiver, scope = method_call_tag.values_at(:name, :receiver, :scope) scope = scope.join("::") if receiver == :class scope = "Kernel" if scope.empty? new_method_path(scope, :class, name) elsif receiver == :instance scope = "Kernel" if scope.empty? new_method_path(scope, :instance, name) else receiver = receiver.join("::") new_method_path(Reflexive.constant_lookup(receiver, scope), :class, name) end # if receiver.last == :instance # new_method_path(receiver[0..-2].join("::"), :instance, name) # else # new_method_path(receiver.join("::"), :class, name) # end rescue(r(method_call_tag)) end
ruby
def method_call_path(method_call_tag) # r method_call_tag.values_at(:name, :receiver) name, receiver, scope = method_call_tag.values_at(:name, :receiver, :scope) scope = scope.join("::") if receiver == :class scope = "Kernel" if scope.empty? new_method_path(scope, :class, name) elsif receiver == :instance scope = "Kernel" if scope.empty? new_method_path(scope, :instance, name) else receiver = receiver.join("::") new_method_path(Reflexive.constant_lookup(receiver, scope), :class, name) end # if receiver.last == :instance # new_method_path(receiver[0..-2].join("::"), :instance, name) # else # new_method_path(receiver.join("::"), :class, name) # end rescue(r(method_call_tag)) end
[ "def", "method_call_path", "(", "method_call_tag", ")", "name", ",", "receiver", ",", "scope", "=", "method_call_tag", ".", "values_at", "(", ":name", ",", ":receiver", ",", ":scope", ")", "scope", "=", "scope", ".", "join", "(", "\"::\"", ")", "if", "receiver", "==", ":class", "scope", "=", "\"Kernel\"", "if", "scope", ".", "empty?", "new_method_path", "(", "scope", ",", ":class", ",", "name", ")", "elsif", "receiver", "==", ":instance", "scope", "=", "\"Kernel\"", "if", "scope", ".", "empty?", "new_method_path", "(", "scope", ",", ":instance", ",", "name", ")", "else", "receiver", "=", "receiver", ".", "join", "(", "\"::\"", ")", "new_method_path", "(", "Reflexive", ".", "constant_lookup", "(", "receiver", ",", "scope", ")", ",", ":class", ",", "name", ")", "end", "end" ]
method_call_tag is the scanner event tag emitted by ReflexiveRipper
[ "method_call_tag", "is", "the", "scanner", "event", "tag", "emitted", "by", "ReflexiveRipper" ]
04a58ba2f45c15e2815b7ca04a78a5b6b89a52b9
https://github.com/dolzenko/reflexive/blob/04a58ba2f45c15e2815b7ca04a78a5b6b89a52b9/lib/reflexive/routing_helpers.rb#L6-L27
train
amoghe/rb_tuntap
lib/rb_tuntap.rb
RbTunTap.Device.validate_address!
def validate_address!(addr) ip = IPAddr.new(addr) unless ip.ipv4? raise NotImplementedError, 'Only IPv4 is supported by this library' end if addr.include?('/') raise ArgumentError, 'Please specify a host IP address (without mask)' end addr.to_s end
ruby
def validate_address!(addr) ip = IPAddr.new(addr) unless ip.ipv4? raise NotImplementedError, 'Only IPv4 is supported by this library' end if addr.include?('/') raise ArgumentError, 'Please specify a host IP address (without mask)' end addr.to_s end
[ "def", "validate_address!", "(", "addr", ")", "ip", "=", "IPAddr", ".", "new", "(", "addr", ")", "unless", "ip", ".", "ipv4?", "raise", "NotImplementedError", ",", "'Only IPv4 is supported by this library'", "end", "if", "addr", ".", "include?", "(", "'/'", ")", "raise", "ArgumentError", ",", "'Please specify a host IP address (without mask)'", "end", "addr", ".", "to_s", "end" ]
Validate that the given string is a valid IP address. @raises ArgumentError, NotImplementedError
[ "Validate", "that", "the", "given", "string", "is", "a", "valid", "IP", "address", "." ]
6eaed110049ea75ec7131bbdc62b49afd9e19489
https://github.com/amoghe/rb_tuntap/blob/6eaed110049ea75ec7131bbdc62b49afd9e19489/lib/rb_tuntap.rb#L90-L102
train
ArchimediaZerogroup/KonoUtils
lib/kono_utils/search_attribute.rb
KonoUtils.SearchAttribute.cast_value
def cast_value(value) return value if value.blank? return value if form_options.is_a? Proc return field_options[:cast].call(value) if field_options[:cast].is_a? Proc case form_options[:as] when :bs_datetimepicker if value.is_a? String DateTime.parse(value) elsif value.is_a? Date value.to_time else value end when :bs_datepicker if value.is_a? String DateTime.parse(value).to_date elsif value.is_a? DateTime value.to_date else value end else value end end
ruby
def cast_value(value) return value if value.blank? return value if form_options.is_a? Proc return field_options[:cast].call(value) if field_options[:cast].is_a? Proc case form_options[:as] when :bs_datetimepicker if value.is_a? String DateTime.parse(value) elsif value.is_a? Date value.to_time else value end when :bs_datepicker if value.is_a? String DateTime.parse(value).to_date elsif value.is_a? DateTime value.to_date else value end else value end end
[ "def", "cast_value", "(", "value", ")", "return", "value", "if", "value", ".", "blank?", "return", "value", "if", "form_options", ".", "is_a?", "Proc", "return", "field_options", "[", ":cast", "]", ".", "call", "(", "value", ")", "if", "field_options", "[", ":cast", "]", ".", "is_a?", "Proc", "case", "form_options", "[", ":as", "]", "when", ":bs_datetimepicker", "if", "value", ".", "is_a?", "String", "DateTime", ".", "parse", "(", "value", ")", "elsif", "value", ".", "is_a?", "Date", "value", ".", "to_time", "else", "value", "end", "when", ":bs_datepicker", "if", "value", ".", "is_a?", "String", "DateTime", ".", "parse", "(", "value", ")", ".", "to_date", "elsif", "value", ".", "is_a?", "DateTime", "value", ".", "to_date", "else", "value", "end", "else", "value", "end", "end" ]
Esegue un casting dei valori rispetto al tipo di campo da utilizzare per formtastic
[ "Esegue", "un", "casting", "dei", "valori", "rispetto", "al", "tipo", "di", "campo", "da", "utilizzare", "per", "formtastic" ]
a255a30b65e4e0f01cd6236d991da4fd13c64fc6
https://github.com/ArchimediaZerogroup/KonoUtils/blob/a255a30b65e4e0f01cd6236d991da4fd13c64fc6/lib/kono_utils/search_attribute.rb#L30-L55
train
CDLUC3/resync-client
lib/resync/client.rb
Resync.Client.get
def get(uri) uri = Resync::XML.to_uri(uri) @helper.fetch(uri: uri) end
ruby
def get(uri) uri = Resync::XML.to_uri(uri) @helper.fetch(uri: uri) end
[ "def", "get", "(", "uri", ")", "uri", "=", "Resync", "::", "XML", ".", "to_uri", "(", "uri", ")", "@helper", ".", "fetch", "(", "uri", ":", "uri", ")", "end" ]
Gets the content of the specified URI as a string. @param uri [URI, String] the URI to download @return [String] the content of the URI
[ "Gets", "the", "content", "of", "the", "specified", "URI", "as", "a", "string", "." ]
e621c9d0c8b8de436923359d6ad36f74c89bb2c2
https://github.com/CDLUC3/resync-client/blob/e621c9d0c8b8de436923359d6ad36f74c89bb2c2/lib/resync/client.rb#L36-L39
train
CDLUC3/resync-client
lib/resync/client.rb
Resync.Client.download_to_temp_file
def download_to_temp_file(uri) uri = Resync::XML.to_uri(uri) @helper.fetch_to_file(uri: uri) end
ruby
def download_to_temp_file(uri) uri = Resync::XML.to_uri(uri) @helper.fetch_to_file(uri: uri) end
[ "def", "download_to_temp_file", "(", "uri", ")", "uri", "=", "Resync", "::", "XML", ".", "to_uri", "(", "uri", ")", "@helper", ".", "fetch_to_file", "(", "uri", ":", "uri", ")", "end" ]
Gets the content of the specified URI and saves it to a temporary file. @param uri [URI, String] the URI to download @return [String] the path to the downloaded file
[ "Gets", "the", "content", "of", "the", "specified", "URI", "and", "saves", "it", "to", "a", "temporary", "file", "." ]
e621c9d0c8b8de436923359d6ad36f74c89bb2c2
https://github.com/CDLUC3/resync-client/blob/e621c9d0c8b8de436923359d6ad36f74c89bb2c2/lib/resync/client.rb#L44-L47
train
CDLUC3/resync-client
lib/resync/client.rb
Resync.Client.download_to_file
def download_to_file(uri:, path:) uri = Resync::XML.to_uri(uri) @helper.fetch_to_file(path: path, uri: uri) end
ruby
def download_to_file(uri:, path:) uri = Resync::XML.to_uri(uri) @helper.fetch_to_file(path: path, uri: uri) end
[ "def", "download_to_file", "(", "uri", ":", ",", "path", ":", ")", "uri", "=", "Resync", "::", "XML", ".", "to_uri", "(", "uri", ")", "@helper", ".", "fetch_to_file", "(", "path", ":", "path", ",", "uri", ":", "uri", ")", "end" ]
Gets the content of the specified URI and saves it to the specified file, overwriting it if it exists. @param uri [URI, String] the URI to download @param path [String] the path to save the download to @return [String] the path to the downloaded file
[ "Gets", "the", "content", "of", "the", "specified", "URI", "and", "saves", "it", "to", "the", "specified", "file", "overwriting", "it", "if", "it", "exists", "." ]
e621c9d0c8b8de436923359d6ad36f74c89bb2c2
https://github.com/CDLUC3/resync-client/blob/e621c9d0c8b8de436923359d6ad36f74c89bb2c2/lib/resync/client.rb#L54-L57
train
ideonetwork/lato-core
lib/lato_core/interfaces/modules.rb
LatoCore.Interface::Modules.core__get_modules_list
def core__get_modules_list all_gems = core__get_application_gems.keys lato_gems = [] # check every gem all_gems.each do |name| lato_gems.push(name) if name.start_with? 'lato' end # return result lato_gems end
ruby
def core__get_modules_list all_gems = core__get_application_gems.keys lato_gems = [] # check every gem all_gems.each do |name| lato_gems.push(name) if name.start_with? 'lato' end # return result lato_gems end
[ "def", "core__get_modules_list", "all_gems", "=", "core__get_application_gems", ".", "keys", "lato_gems", "=", "[", "]", "all_gems", ".", "each", "do", "|", "name", "|", "lato_gems", ".", "push", "(", "name", ")", "if", "name", ".", "start_with?", "'lato'", "end", "lato_gems", "end" ]
This function returns the list of lato modules installed on main application.
[ "This", "function", "returns", "the", "list", "of", "lato", "modules", "installed", "on", "main", "application", "." ]
c01fa585725c8e9992f25d8a7bd4ba2d0bfca08c
https://github.com/ideonetwork/lato-core/blob/c01fa585725c8e9992f25d8a7bd4ba2d0bfca08c/lib/lato_core/interfaces/modules.rb#L15-L24
train
ideonetwork/lato-core
lib/lato_core/interfaces/modules.rb
LatoCore.Interface::Modules.core__get_module_languages
def core__get_module_languages(module_name) default_languages = core__get_module_default_languages(module_name) application_languages = core__get_module_application_languages(module_name) return default_languages unless application_languages default_languages.each do |key, value| application_languages[key] = value unless application_languages[key] end application_languages end
ruby
def core__get_module_languages(module_name) default_languages = core__get_module_default_languages(module_name) application_languages = core__get_module_application_languages(module_name) return default_languages unless application_languages default_languages.each do |key, value| application_languages[key] = value unless application_languages[key] end application_languages end
[ "def", "core__get_module_languages", "(", "module_name", ")", "default_languages", "=", "core__get_module_default_languages", "(", "module_name", ")", "application_languages", "=", "core__get_module_application_languages", "(", "module_name", ")", "return", "default_languages", "unless", "application_languages", "default_languages", ".", "each", "do", "|", "key", ",", "value", "|", "application_languages", "[", "key", "]", "=", "value", "unless", "application_languages", "[", "key", "]", "end", "application_languages", "end" ]
This function load languages for a specific module. This config are generated from the merge of application languages for the module and default languages of the module.
[ "This", "function", "load", "languages", "for", "a", "specific", "module", ".", "This", "config", "are", "generated", "from", "the", "merge", "of", "application", "languages", "for", "the", "module", "and", "default", "languages", "of", "the", "module", "." ]
c01fa585725c8e9992f25d8a7bd4ba2d0bfca08c
https://github.com/ideonetwork/lato-core/blob/c01fa585725c8e9992f25d8a7bd4ba2d0bfca08c/lib/lato_core/interfaces/modules.rb#L42-L52
train
ideonetwork/lato-core
lib/lato_core/interfaces/modules.rb
LatoCore.Interface::Modules.core__get_module_configs
def core__get_module_configs module_name default_config = core__get_module_default_configs(module_name) application_config = core__get_module_application_configs(module_name) return default_config unless application_config default_config.each do |key, value| application_config[key] = value unless application_config[key] end return application_config end
ruby
def core__get_module_configs module_name default_config = core__get_module_default_configs(module_name) application_config = core__get_module_application_configs(module_name) return default_config unless application_config default_config.each do |key, value| application_config[key] = value unless application_config[key] end return application_config end
[ "def", "core__get_module_configs", "module_name", "default_config", "=", "core__get_module_default_configs", "(", "module_name", ")", "application_config", "=", "core__get_module_application_configs", "(", "module_name", ")", "return", "default_config", "unless", "application_config", "default_config", ".", "each", "do", "|", "key", ",", "value", "|", "application_config", "[", "key", "]", "=", "value", "unless", "application_config", "[", "key", "]", "end", "return", "application_config", "end" ]
This function load configs for a specific module. This configs are generated from the merge of application configs for the module and default configs of the module.
[ "This", "function", "load", "configs", "for", "a", "specific", "module", ".", "This", "configs", "are", "generated", "from", "the", "merge", "of", "application", "configs", "for", "the", "module", "and", "default", "configs", "of", "the", "module", "." ]
c01fa585725c8e9992f25d8a7bd4ba2d0bfca08c
https://github.com/ideonetwork/lato-core/blob/c01fa585725c8e9992f25d8a7bd4ba2d0bfca08c/lib/lato_core/interfaces/modules.rb#L83-L93
train
sinefunc/lunar
lib/lunar/index.rb
Lunar.Index.text
def text(att, value) clear_text_field(att) Scoring.new(value).scores.each do |word, score| metaphone = Lunar.metaphone(word) nest[att][metaphone].zadd(score, id) metaphones[id][att].sadd(metaphone) end fields[TEXT].sadd(att) end
ruby
def text(att, value) clear_text_field(att) Scoring.new(value).scores.each do |word, score| metaphone = Lunar.metaphone(word) nest[att][metaphone].zadd(score, id) metaphones[id][att].sadd(metaphone) end fields[TEXT].sadd(att) end
[ "def", "text", "(", "att", ",", "value", ")", "clear_text_field", "(", "att", ")", "Scoring", ".", "new", "(", "value", ")", ".", "scores", ".", "each", "do", "|", "word", ",", "score", "|", "metaphone", "=", "Lunar", ".", "metaphone", "(", "word", ")", "nest", "[", "att", "]", "[", "metaphone", "]", ".", "zadd", "(", "score", ",", "id", ")", "metaphones", "[", "id", "]", "[", "att", "]", ".", "sadd", "(", "metaphone", ")", "end", "fields", "[", "TEXT", "]", ".", "sadd", "(", "att", ")", "end" ]
Indexes all the metaphone equivalents of the words in value except for words included in Stopwords. @example Lunar.index :Gadget do |i| i.id 1001 i.text :title, "apple macbook pro" end # Executes the ff: in redis: # ZADD Lunar:Gadget:title:APL 1 1001 # ZADD Lunar:Gadget:title:MKBK 1 1001 # ZADD Lunar:Gadget:title:PR 1 1001 # In addition a reference of all the words are stored # SMEMBERS Lunar:Gadget:Metaphones:1001:title # => (APL, MKBK, PR) @param [Symbol] att the field name in your document @param [String] value the content of the field name @return [Array<String>] all the metaphones added for the document.
[ "Indexes", "all", "the", "metaphone", "equivalents", "of", "the", "words", "in", "value", "except", "for", "words", "included", "in", "Stopwords", "." ]
efc58f392dd75e771d313eef6cd4ada0d1ac02ff
https://github.com/sinefunc/lunar/blob/efc58f392dd75e771d313eef6cd4ada0d1ac02ff/lib/lunar/index.rb#L105-L116
train
sinefunc/lunar
lib/lunar/index.rb
Lunar.Index.number
def number(att, value, purge = true) if value.kind_of?(Enumerable) clear_number_field(att) value.each { |v| number(att, v, false) } and return end clear_number_field(att) if purge numbers[att].zadd(value, id) numbers[att][value].zadd(1, id) numbers[id][att].sadd(value) fields[NUMBERS].sadd att end
ruby
def number(att, value, purge = true) if value.kind_of?(Enumerable) clear_number_field(att) value.each { |v| number(att, v, false) } and return end clear_number_field(att) if purge numbers[att].zadd(value, id) numbers[att][value].zadd(1, id) numbers[id][att].sadd(value) fields[NUMBERS].sadd att end
[ "def", "number", "(", "att", ",", "value", ",", "purge", "=", "true", ")", "if", "value", ".", "kind_of?", "(", "Enumerable", ")", "clear_number_field", "(", "att", ")", "value", ".", "each", "{", "|", "v", "|", "number", "(", "att", ",", "v", ",", "false", ")", "}", "and", "return", "end", "clear_number_field", "(", "att", ")", "if", "purge", "numbers", "[", "att", "]", ".", "zadd", "(", "value", ",", "id", ")", "numbers", "[", "att", "]", "[", "value", "]", ".", "zadd", "(", "1", ",", "id", ")", "numbers", "[", "id", "]", "[", "att", "]", ".", "sadd", "(", "value", ")", "fields", "[", "NUMBERS", "]", ".", "sadd", "att", "end" ]
Adds a numeric index for `att` with `value`. @example Lunar.index :Gadget do |i| i.id 1001 i.number :price, 200 end # Executes the ff: in redis: # ZADD Lunar:Gadget:price 200 @param [Symbol] att the field name in your document. @param [Numeric] value the numeric value of `att`. @return [Boolean] whether or not the value was added
[ "Adds", "a", "numeric", "index", "for", "att", "with", "value", "." ]
efc58f392dd75e771d313eef6cd4ada0d1ac02ff
https://github.com/sinefunc/lunar/blob/efc58f392dd75e771d313eef6cd4ada0d1ac02ff/lib/lunar/index.rb#L135-L149
train
sinefunc/lunar
lib/lunar/index.rb
Lunar.Index.sortable
def sortable(att, value) sortables[id][att].set(value) fields[SORTABLES].sadd att end
ruby
def sortable(att, value) sortables[id][att].set(value) fields[SORTABLES].sadd att end
[ "def", "sortable", "(", "att", ",", "value", ")", "sortables", "[", "id", "]", "[", "att", "]", ".", "set", "(", "value", ")", "fields", "[", "SORTABLES", "]", ".", "sadd", "att", "end" ]
Adds a sortable index for `att` with `value`. @example class Gadget def self.[](id) # find the gadget using id here end end Lunar.index Gadget do |i| i.id 1001 i.text 'apple macbook pro' i.sortable :votes, 50 end Lunar.index Gadget do |i| i.id 1002 i.text 'apple iphone 3g' i.sortable :votes, 20 end results = Lunar.search(Gadget, :q => 'apple') results.sort(:by => :votes, :order => 'DESC') # returns [Gadget[1001], Gadget[1002]] results.sort(:by => :votes, :order => 'ASC') # returns [Gadget[1002], Gadget[1001]] @param [Symbol] att the field you want to have sortability. @param [String, Numeric] value the value of the sortable field. @return [String] the response from the redis server.
[ "Adds", "a", "sortable", "index", "for", "att", "with", "value", "." ]
efc58f392dd75e771d313eef6cd4ada0d1ac02ff
https://github.com/sinefunc/lunar/blob/efc58f392dd75e771d313eef6cd4ada0d1ac02ff/lib/lunar/index.rb#L184-L188
train
snusnu/substation
lib/substation/request.rb
Substation.Request.to_request
def to_request(new_input = Undefined) new_input.equal?(Undefined) ? self : self.class.new(name, env, new_input) end
ruby
def to_request(new_input = Undefined) new_input.equal?(Undefined) ? self : self.class.new(name, env, new_input) end
[ "def", "to_request", "(", "new_input", "=", "Undefined", ")", "new_input", ".", "equal?", "(", "Undefined", ")", "?", "self", ":", "self", ".", "class", ".", "new", "(", "name", ",", "env", ",", "new_input", ")", "end" ]
Return self or a new instance with +input+ @param [Object] input the input for the new instance @return [self] if +input+ is {Undefined} @return [Request] a new instance with +input+ @api private
[ "Return", "self", "or", "a", "new", "instance", "with", "+", "input", "+" ]
fabf062a3640f5e82dae68597f0709b63f6b9027
https://github.com/snusnu/substation/blob/fabf062a3640f5e82dae68597f0709b63f6b9027/lib/substation/request.rb#L81-L83
train
ideonetwork/lato-core
lib/lato_core/interfaces/token.rb
LatoCore.Interface::Token.core__encode_token
def core__encode_token exp, payload exp = 1.day.from_now unless exp payload[:exp] = exp.to_i JWT.encode(payload, Rails.application.secrets.secret_key_base, 'HS256') end
ruby
def core__encode_token exp, payload exp = 1.day.from_now unless exp payload[:exp] = exp.to_i JWT.encode(payload, Rails.application.secrets.secret_key_base, 'HS256') end
[ "def", "core__encode_token", "exp", ",", "payload", "exp", "=", "1", ".", "day", ".", "from_now", "unless", "exp", "payload", "[", ":exp", "]", "=", "exp", ".", "to_i", "JWT", ".", "encode", "(", "payload", ",", "Rails", ".", "application", ".", "secrets", ".", "secret_key_base", ",", "'HS256'", ")", "end" ]
This functon return a token with encrypted payload information.
[ "This", "functon", "return", "a", "token", "with", "encrypted", "payload", "information", "." ]
c01fa585725c8e9992f25d8a7bd4ba2d0bfca08c
https://github.com/ideonetwork/lato-core/blob/c01fa585725c8e9992f25d8a7bd4ba2d0bfca08c/lib/lato_core/interfaces/token.rb#L8-L12
train
ideonetwork/lato-core
lib/lato_core/interfaces/token.rb
LatoCore.Interface::Token.core__decode_token
def core__decode_token token begin body = JWT.decode(token, Rails.application.secrets.secret_key_base, true, algorithm: 'HS256')[0] return HashWithIndifferentAccess.new body rescue => exception return nil end end
ruby
def core__decode_token token begin body = JWT.decode(token, Rails.application.secrets.secret_key_base, true, algorithm: 'HS256')[0] return HashWithIndifferentAccess.new body rescue => exception return nil end end
[ "def", "core__decode_token", "token", "begin", "body", "=", "JWT", ".", "decode", "(", "token", ",", "Rails", ".", "application", ".", "secrets", ".", "secret_key_base", ",", "true", ",", "algorithm", ":", "'HS256'", ")", "[", "0", "]", "return", "HashWithIndifferentAccess", ".", "new", "body", "rescue", "=>", "exception", "return", "nil", "end", "end" ]
This function return the payload of a token.
[ "This", "function", "return", "the", "payload", "of", "a", "token", "." ]
c01fa585725c8e9992f25d8a7bd4ba2d0bfca08c
https://github.com/ideonetwork/lato-core/blob/c01fa585725c8e9992f25d8a7bd4ba2d0bfca08c/lib/lato_core/interfaces/token.rb#L15-L23
train
threez/marilyn-rpc
lib/marilyn-rpc/client.rb
MarilynRPC.NativeClient.authenticate
def authenticate(username, password, method = :plain) execute(MarilynRPC::Service::AUTHENTICATION_PATH, "authenticate_#{method}".to_sym, [username, password]) end
ruby
def authenticate(username, password, method = :plain) execute(MarilynRPC::Service::AUTHENTICATION_PATH, "authenticate_#{method}".to_sym, [username, password]) end
[ "def", "authenticate", "(", "username", ",", "password", ",", "method", "=", ":plain", ")", "execute", "(", "MarilynRPC", "::", "Service", "::", "AUTHENTICATION_PATH", ",", "\"authenticate_#{method}\"", ".", "to_sym", ",", "[", "username", ",", "password", "]", ")", "end" ]
authenicate the client to call methods that require authentication @param [String] username the username of the client @param [String] password the password of the client @param [Symbol] method the method to use for authentication, currently only plain is supported. So make sure you are using a secure socket.
[ "authenicate", "the", "client", "to", "call", "methods", "that", "require", "authentication" ]
e75b46b7dfe5040f4a5022b23702b5a29cf4844f
https://github.com/threez/marilyn-rpc/blob/e75b46b7dfe5040f4a5022b23702b5a29cf4844f/lib/marilyn-rpc/client.rb#L74-L77
train
threez/marilyn-rpc
lib/marilyn-rpc/client.rb
MarilynRPC.NativeClient.execute
def execute(path, method, args) thread = Thread.current tag = "#{Time.now.to_f}:#{thread.object_id}" @semaphore.synchronize { # since this client can't multiplex, we set the tag to nil @socket.write(MarilynRPC::MailFactory.build_call(tag, path, method, args)) # lets write our self to the list of waining threads @threads[tag] = thread } # stop the current thread, the thread will be started after the response # arrived Thread.stop # get mail from responses mail = thread[MAIL_KEY] if mail.is_a? MarilynRPC::CallResponseMail mail.result else raise MarilynError.new # raise exception to capture the client backtrace end rescue MarilynError => exception # add local and remote trace together and reraise the original exception backtrace = [] backtrace += exception.backtrace backtrace += mail.exception.backtrace mail.exception.set_backtrace(backtrace) raise mail.exception end
ruby
def execute(path, method, args) thread = Thread.current tag = "#{Time.now.to_f}:#{thread.object_id}" @semaphore.synchronize { # since this client can't multiplex, we set the tag to nil @socket.write(MarilynRPC::MailFactory.build_call(tag, path, method, args)) # lets write our self to the list of waining threads @threads[tag] = thread } # stop the current thread, the thread will be started after the response # arrived Thread.stop # get mail from responses mail = thread[MAIL_KEY] if mail.is_a? MarilynRPC::CallResponseMail mail.result else raise MarilynError.new # raise exception to capture the client backtrace end rescue MarilynError => exception # add local and remote trace together and reraise the original exception backtrace = [] backtrace += exception.backtrace backtrace += mail.exception.backtrace mail.exception.set_backtrace(backtrace) raise mail.exception end
[ "def", "execute", "(", "path", ",", "method", ",", "args", ")", "thread", "=", "Thread", ".", "current", "tag", "=", "\"#{Time.now.to_f}:#{thread.object_id}\"", "@semaphore", ".", "synchronize", "{", "@socket", ".", "write", "(", "MarilynRPC", "::", "MailFactory", ".", "build_call", "(", "tag", ",", "path", ",", "method", ",", "args", ")", ")", "@threads", "[", "tag", "]", "=", "thread", "}", "Thread", ".", "stop", "mail", "=", "thread", "[", "MAIL_KEY", "]", "if", "mail", ".", "is_a?", "MarilynRPC", "::", "CallResponseMail", "mail", ".", "result", "else", "raise", "MarilynError", ".", "new", "end", "rescue", "MarilynError", "=>", "exception", "backtrace", "=", "[", "]", "backtrace", "+=", "exception", ".", "backtrace", "backtrace", "+=", "mail", ".", "exception", ".", "backtrace", "mail", ".", "exception", ".", "set_backtrace", "(", "backtrace", ")", "raise", "mail", ".", "exception", "end" ]
Executes a client call blocking. To issue an async call one needs to have start separate threads. THe Native client uses then multiplexing to avoid the other threads blocking. @api private @param [Object] path the path to identifiy the service @param [Symbol, String] method the method name to call on the service @param [Array<Object>] args the arguments that are passed to the remote side @return [Object] the result of the call
[ "Executes", "a", "client", "call", "blocking", ".", "To", "issue", "an", "async", "call", "one", "needs", "to", "have", "start", "separate", "threads", ".", "THe", "Native", "client", "uses", "then", "multiplexing", "to", "avoid", "the", "other", "threads", "blocking", "." ]
e75b46b7dfe5040f4a5022b23702b5a29cf4844f
https://github.com/threez/marilyn-rpc/blob/e75b46b7dfe5040f4a5022b23702b5a29cf4844f/lib/marilyn-rpc/client.rb#L130-L161
train
brianmichel/BadFruit
lib/badfruit/Movies/movies.rb
BadFruit.Movies.search_by_name
def search_by_name(name, page_limit=1, page=1) if page_limit > 50 page_limit = MAX_PAGE_LIMIT #current limitation of the rotten tomatos API end results_json = @badfruit.search_movies(name, page_limit, page) if results_json.nil? return [] else return @badfruit.parse_movies_array(JSON.parse(results_json)) end end
ruby
def search_by_name(name, page_limit=1, page=1) if page_limit > 50 page_limit = MAX_PAGE_LIMIT #current limitation of the rotten tomatos API end results_json = @badfruit.search_movies(name, page_limit, page) if results_json.nil? return [] else return @badfruit.parse_movies_array(JSON.parse(results_json)) end end
[ "def", "search_by_name", "(", "name", ",", "page_limit", "=", "1", ",", "page", "=", "1", ")", "if", "page_limit", ">", "50", "page_limit", "=", "MAX_PAGE_LIMIT", "end", "results_json", "=", "@badfruit", ".", "search_movies", "(", "name", ",", "page_limit", ",", "page", ")", "if", "results_json", ".", "nil?", "return", "[", "]", "else", "return", "@badfruit", ".", "parse_movies_array", "(", "JSON", ".", "parse", "(", "results_json", ")", ")", "end", "end" ]
Initialize a wrapper around the Rotten Tomatoes API specific to movies. Search for a movie by name. @param [String] name The name of the movie to search for. @param [Integer] page_limit The number of results to return for API response page. (Defaults to 1) @param [Integer] page The page offset to request from the API. (Defaults to 1) @return [Array<BadFruit::Movie>] An array of movie objects matching the name parameter.
[ "Initialize", "a", "wrapper", "around", "the", "Rotten", "Tomatoes", "API", "specific", "to", "movies", "." ]
dab9c28d4bcd79d64829239abf6a816bbbcc73a6
https://github.com/brianmichel/BadFruit/blob/dab9c28d4bcd79d64829239abf6a816bbbcc73a6/lib/badfruit/Movies/movies.rb#L25-L36
train
brianmichel/BadFruit
lib/badfruit/Movies/movies.rb
BadFruit.Movies.search_by_id
def search_by_id(movie_id) movie = @badfruit.get_movie_info(movie_id, "main") raise 'Movie not found' if movie.nil? || movie.empty? @badfruit.parse_movie_array(JSON.parse(movie)) end
ruby
def search_by_id(movie_id) movie = @badfruit.get_movie_info(movie_id, "main") raise 'Movie not found' if movie.nil? || movie.empty? @badfruit.parse_movie_array(JSON.parse(movie)) end
[ "def", "search_by_id", "(", "movie_id", ")", "movie", "=", "@badfruit", ".", "get_movie_info", "(", "movie_id", ",", "\"main\"", ")", "raise", "'Movie not found'", "if", "movie", ".", "nil?", "||", "movie", ".", "empty?", "@badfruit", ".", "parse_movie_array", "(", "JSON", ".", "parse", "(", "movie", ")", ")", "end" ]
search by id Search for a movie by Rotten Tomatoes id. @param [String] movie_id The id of the movie to search for. @return [BadFruit::Movie] A movie object from the response data.
[ "search", "by", "id" ]
dab9c28d4bcd79d64829239abf6a816bbbcc73a6
https://github.com/brianmichel/BadFruit/blob/dab9c28d4bcd79d64829239abf6a816bbbcc73a6/lib/badfruit/Movies/movies.rb#L47-L51
train
brianmichel/BadFruit
lib/badfruit/Movies/movies.rb
BadFruit.Movies.search_by_alias
def search_by_alias(alias_id, type='imdb') movie = @badfruit.get_movie_alias_info(alias_id, type) json = JSON.parse(movie) raise 'Movie not found' if !json['error'].nil? @badfruit.parse_movie_array(json) end
ruby
def search_by_alias(alias_id, type='imdb') movie = @badfruit.get_movie_alias_info(alias_id, type) json = JSON.parse(movie) raise 'Movie not found' if !json['error'].nil? @badfruit.parse_movie_array(json) end
[ "def", "search_by_alias", "(", "alias_id", ",", "type", "=", "'imdb'", ")", "movie", "=", "@badfruit", ".", "get_movie_alias_info", "(", "alias_id", ",", "type", ")", "json", "=", "JSON", ".", "parse", "(", "movie", ")", "raise", "'Movie not found'", "if", "!", "json", "[", "'error'", "]", ".", "nil?", "@badfruit", ".", "parse_movie_array", "(", "json", ")", "end" ]
Search for a movie by way of a 3rd party id. @param [String] alias_id The alias id of the movie. @param [String] type The type of alias id that is being provided. (Defaults to 'imdb') @return [BadFruit::Movie] A movie object representing the 3rd party id. @note Currently only 'imdb' as a type is supported.
[ "Search", "for", "a", "movie", "by", "way", "of", "a", "3rd", "party", "id", "." ]
dab9c28d4bcd79d64829239abf6a816bbbcc73a6
https://github.com/brianmichel/BadFruit/blob/dab9c28d4bcd79d64829239abf6a816bbbcc73a6/lib/badfruit/Movies/movies.rb#L62-L67
train
onesky/one_sky-ruby
lib/one_sky/translation.rb
OneSky.Translation.dashify_string_hash
def dashify_string_hash(string_hash) output = Hash.new string_hash.each do |key, value| dashed = key.to_s.gsub("_", "-").to_sym output[dashed] = value end output end
ruby
def dashify_string_hash(string_hash) output = Hash.new string_hash.each do |key, value| dashed = key.to_s.gsub("_", "-").to_sym output[dashed] = value end output end
[ "def", "dashify_string_hash", "(", "string_hash", ")", "output", "=", "Hash", ".", "new", "string_hash", ".", "each", "do", "|", "key", ",", "value", "|", "dashed", "=", "key", ".", "to_s", ".", "gsub", "(", "\"_\"", ",", "\"-\"", ")", ".", "to_sym", "output", "[", "dashed", "]", "=", "value", "end", "output", "end" ]
convert to "string-key" not "string_key"
[ "convert", "to", "string", "-", "key", "not", "string_key" ]
cc1ae294073086b7aab66340416062aaee59a160
https://github.com/onesky/one_sky-ruby/blob/cc1ae294073086b7aab66340416062aaee59a160/lib/one_sky/translation.rb#L131-L138
train
sunlightlabs/ruby-sunlight
lib/sunlight/legislator.rb
Sunlight.Legislator.committees
def committees url = Sunlight::Base.construct_url("committees.allForLegislator", {:bioguide_id => self.bioguide_id}) if (result = Sunlight::Base.get_json_data(url)) committees = [] result["response"]["committees"].each do |committee| committees << Sunlight::Committee.new(committee["committee"]) end else nil # appropriate params not found end committees end
ruby
def committees url = Sunlight::Base.construct_url("committees.allForLegislator", {:bioguide_id => self.bioguide_id}) if (result = Sunlight::Base.get_json_data(url)) committees = [] result["response"]["committees"].each do |committee| committees << Sunlight::Committee.new(committee["committee"]) end else nil # appropriate params not found end committees end
[ "def", "committees", "url", "=", "Sunlight", "::", "Base", ".", "construct_url", "(", "\"committees.allForLegislator\"", ",", "{", ":bioguide_id", "=>", "self", ".", "bioguide_id", "}", ")", "if", "(", "result", "=", "Sunlight", "::", "Base", ".", "get_json_data", "(", "url", ")", ")", "committees", "=", "[", "]", "result", "[", "\"response\"", "]", "[", "\"committees\"", "]", ".", "each", "do", "|", "committee", "|", "committees", "<<", "Sunlight", "::", "Committee", ".", "new", "(", "committee", "[", "\"committee\"", "]", ")", "end", "else", "nil", "end", "committees", "end" ]
Get the committees the Legislator sits on Returns: An array of Committee objects, each possibly having its own subarray of subcommittees
[ "Get", "the", "committees", "the", "Legislator", "sits", "on" ]
239063ccf26fadaf64d650fd3c22bcc734cc3394
https://github.com/sunlightlabs/ruby-sunlight/blob/239063ccf26fadaf64d650fd3c22bcc734cc3394/lib/sunlight/legislator.rb#L32-L44
train
seejohnrun/console_tweet
lib/console_tweet/cli.rb
ConsoleTweet.CLI.get_access_token
def get_access_token @client = TwitterOAuth::Client.new(:consumer_key => ConsumerKey, :consumer_secret => ConsumerSecret) request_token = @client.request_token # ask the user to visit the auth url puts "To authenticate your client, visit the URL: #{request_token.authorize_url}" open_link request_token.authorize_url # wait for the user to give us the PIN back print 'Enter PIN: ' begin @client.authorize(request_token.token, request_token.secret, :oauth_verifier => self.class.get_input.chomp) rescue OAuth::Unauthorized false # Didn't get an access token end end
ruby
def get_access_token @client = TwitterOAuth::Client.new(:consumer_key => ConsumerKey, :consumer_secret => ConsumerSecret) request_token = @client.request_token # ask the user to visit the auth url puts "To authenticate your client, visit the URL: #{request_token.authorize_url}" open_link request_token.authorize_url # wait for the user to give us the PIN back print 'Enter PIN: ' begin @client.authorize(request_token.token, request_token.secret, :oauth_verifier => self.class.get_input.chomp) rescue OAuth::Unauthorized false # Didn't get an access token end end
[ "def", "get_access_token", "@client", "=", "TwitterOAuth", "::", "Client", ".", "new", "(", ":consumer_key", "=>", "ConsumerKey", ",", ":consumer_secret", "=>", "ConsumerSecret", ")", "request_token", "=", "@client", ".", "request_token", "puts", "\"To authenticate your client, visit the URL: #{request_token.authorize_url}\"", "open_link", "request_token", ".", "authorize_url", "print", "'Enter PIN: '", "begin", "@client", ".", "authorize", "(", "request_token", ".", "token", ",", "request_token", ".", "secret", ",", ":oauth_verifier", "=>", "self", ".", "class", ".", "get_input", ".", "chomp", ")", "rescue", "OAuth", "::", "Unauthorized", "false", "end", "end" ]
Prompt the user for a PIN using a request token, and see if we can successfully authenticate them
[ "Prompt", "the", "user", "for", "a", "PIN", "using", "a", "request", "token", "and", "see", "if", "we", "can", "successfully", "authenticate", "them" ]
6920bb0ead3060ac52eb968bc0df3c21b72e1ff6
https://github.com/seejohnrun/console_tweet/blob/6920bb0ead3060ac52eb968bc0df3c21b72e1ff6/lib/console_tweet/cli.rb#L46-L59
train
seejohnrun/console_tweet
lib/console_tweet/cli.rb
ConsoleTweet.CLI.timeline
def timeline(*args) load_default_token return failtown("Unauthorized, re-run setup!") unless @client && @client.authorized? # Only send since_id to @client if it's not nil home_timeline = since_id ? @client.home_timeline(:since_id => since_id) : @client.home_timeline if home_timeline.any? print_tweets(home_timeline) # Save the last id as since_id self.since_id = home_timeline.last['id'] end end
ruby
def timeline(*args) load_default_token return failtown("Unauthorized, re-run setup!") unless @client && @client.authorized? # Only send since_id to @client if it's not nil home_timeline = since_id ? @client.home_timeline(:since_id => since_id) : @client.home_timeline if home_timeline.any? print_tweets(home_timeline) # Save the last id as since_id self.since_id = home_timeline.last['id'] end end
[ "def", "timeline", "(", "*", "args", ")", "load_default_token", "return", "failtown", "(", "\"Unauthorized, re-run setup!\"", ")", "unless", "@client", "&&", "@client", ".", "authorized?", "home_timeline", "=", "since_id", "?", "@client", ".", "home_timeline", "(", ":since_id", "=>", "since_id", ")", ":", "@client", ".", "home_timeline", "if", "home_timeline", ".", "any?", "print_tweets", "(", "home_timeline", ")", "self", ".", "since_id", "=", "home_timeline", ".", "last", "[", "'id'", "]", "end", "end" ]
Display the user's timeline
[ "Display", "the", "user", "s", "timeline" ]
6920bb0ead3060ac52eb968bc0df3c21b72e1ff6
https://github.com/seejohnrun/console_tweet/blob/6920bb0ead3060ac52eb968bc0df3c21b72e1ff6/lib/console_tweet/cli.rb#L62-L72
train