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
list
docstring
stringlengths
8
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
94
266
partition
stringclasses
1 value
david942j/memory_io
lib/memory_io/process.rb
MemoryIO.Process.read
def read(addr, num_elements, **options) mem_io(:read) { |io| io.read(num_elements, from: MemoryIO::Util.safe_eval(addr, bases), **options) } end
ruby
def read(addr, num_elements, **options) mem_io(:read) { |io| io.read(num_elements, from: MemoryIO::Util.safe_eval(addr, bases), **options) } end
[ "def", "read", "(", "addr", ",", "num_elements", ",", "**", "options", ")", "mem_io", "(", ":read", ")", "{", "|", "io", "|", "io", ".", "read", "(", "num_elements", ",", "from", ":", "MemoryIO", "::", "Util", ".", "safe_eval", "(", "addr", ",", "bases", ")", ",", "**", "options", ")", "}", "end" ]
Read from process's memory. This method has *almost* same arguements and return types as {IO#read}. The only difference is this method needs parameter +addr+ (which will be passed to paramter +from+ in {IO#read}). @param [Integer, String] addr The address start to read. When String is given, it will be safe-evaluated. You can use variables such as +'heap'/'stack'/'libc'+ in this parameter. See examples. @param [Integer] num_elements Number of elements to read. See {IO#read}. @return [String, Object, Array<Object>] See {IO#read}. @example process = MemoryIO.attach(`pidof victim`.to_i) puts process.read('heap', 4, as: :u64).map { |c| '0x%016x' % c } # 0x0000000000000000 # 0x0000000000000021 # 0x00000000deadbeef # 0x0000000000000000 #=> nil process.read('heap+0x10', 4, as: :u8).map { |c| '0x%x' % c } #=> ['0xef', '0xbe', '0xad', '0xde'] process.read('libc', 4) #=> "\x7fELF" @see IO#read
[ "Read", "from", "process", "s", "memory", "." ]
97a4206974b699767c57f3e113f78bdae69f950f
https://github.com/david942j/memory_io/blob/97a4206974b699767c57f3e113f78bdae69f950f/lib/memory_io/process.rb#L109-L111
train
david942j/memory_io
lib/memory_io/process.rb
MemoryIO.Process.write
def write(addr, objects, **options) mem_io(:write) { |io| io.write(objects, from: MemoryIO::Util.safe_eval(addr, bases), **options) } end
ruby
def write(addr, objects, **options) mem_io(:write) { |io| io.write(objects, from: MemoryIO::Util.safe_eval(addr, bases), **options) } end
[ "def", "write", "(", "addr", ",", "objects", ",", "**", "options", ")", "mem_io", "(", ":write", ")", "{", "|", "io", "|", "io", ".", "write", "(", "objects", ",", "from", ":", "MemoryIO", "::", "Util", ".", "safe_eval", "(", "addr", ",", "bases", ")", ",", "**", "options", ")", "}", "end" ]
Write objects at +addr+. This method has *almost* same arguments as {IO#write}. @param [Integer, String] addr The address to start to write. See examples. @param [Object, Array<Object>] objects Objects to write. If +objects+ is an array, the write procedure will be invoked +objects.size+ times. @return [void] @example process = MemoryIO.attach('self') s = 'A' * 16 process.write(s.object_id * 2 + 16, 'BBBBCCCC') s #=> 'BBBBCCCCAAAAAAAA' @see IO#write
[ "Write", "objects", "at", "+", "addr", "+", "." ]
97a4206974b699767c57f3e113f78bdae69f950f
https://github.com/david942j/memory_io/blob/97a4206974b699767c57f3e113f78bdae69f950f/lib/memory_io/process.rb#L133-L135
train
openc/turbot-client
lib/turbot/helpers/netrc_helper.rb
Turbot.Helpers.netrc_path
def netrc_path unencrypted = Netrc.default_path encrypted = unencrypted + '.gpg' if File.exists?(encrypted) encrypted else unencrypted end end
ruby
def netrc_path unencrypted = Netrc.default_path encrypted = unencrypted + '.gpg' if File.exists?(encrypted) encrypted else unencrypted end end
[ "def", "netrc_path", "unencrypted", "=", "Netrc", ".", "default_path", "encrypted", "=", "unencrypted", "+", "'.gpg'", "if", "File", ".", "exists?", "(", "encrypted", ")", "encrypted", "else", "unencrypted", "end", "end" ]
Returns the path to the `.netrc` file containing the Turbot host's entry with the user's email address and API key. @return [String] the path to the `.netrc` file
[ "Returns", "the", "path", "to", "the", ".", "netrc", "file", "containing", "the", "Turbot", "host", "s", "entry", "with", "the", "user", "s", "email", "address", "and", "API", "key", "." ]
01225a5c7e155b7b34f1ae8de107c0b97201b42d
https://github.com/openc/turbot-client/blob/01225a5c7e155b7b34f1ae8de107c0b97201b42d/lib/turbot/helpers/netrc_helper.rb#L23-L31
train
openc/turbot-client
lib/turbot/helpers/netrc_helper.rb
Turbot.Helpers.open_netrc
def open_netrc begin Netrc.read(netrc_path) rescue Netrc::Error => e error e.message end end
ruby
def open_netrc begin Netrc.read(netrc_path) rescue Netrc::Error => e error e.message end end
[ "def", "open_netrc", "begin", "Netrc", ".", "read", "(", "netrc_path", ")", "rescue", "Netrc", "::", "Error", "=>", "e", "error", "e", ".", "message", "end", "end" ]
Reads a `.netrc` file. @return [Netrc] the `.netrc` file
[ "Reads", "a", ".", "netrc", "file", "." ]
01225a5c7e155b7b34f1ae8de107c0b97201b42d
https://github.com/openc/turbot-client/blob/01225a5c7e155b7b34f1ae8de107c0b97201b42d/lib/turbot/helpers/netrc_helper.rb#L43-L49
train
openc/turbot-client
lib/turbot/helpers/netrc_helper.rb
Turbot.Helpers.save_netrc_entry
def save_netrc_entry(email_address, api_key) netrc = open_netrc netrc["api.#{host}"] = [email_address, api_key] netrc.save end
ruby
def save_netrc_entry(email_address, api_key) netrc = open_netrc netrc["api.#{host}"] = [email_address, api_key] netrc.save end
[ "def", "save_netrc_entry", "(", "email_address", ",", "api_key", ")", "netrc", "=", "open_netrc", "netrc", "[", "\"api.#{host}\"", "]", "=", "[", "email_address", ",", "api_key", "]", "netrc", ".", "save", "end" ]
Saves the user's email address and AP key to the Turbot host's entry in the `.netrc` file.
[ "Saves", "the", "user", "s", "email", "address", "and", "AP", "key", "to", "the", "Turbot", "host", "s", "entry", "in", "the", ".", "netrc", "file", "." ]
01225a5c7e155b7b34f1ae8de107c0b97201b42d
https://github.com/openc/turbot-client/blob/01225a5c7e155b7b34f1ae8de107c0b97201b42d/lib/turbot/helpers/netrc_helper.rb#L60-L64
train
CocoaPods/Humus
lib/snapshots.rb
Humus.Snapshots.seed_from_dump
def seed_from_dump id target_path = File.expand_path("../../fixtures/trunk-#{id}.dump", __FILE__) raise "Dump #{id} could not be found." unless File.exists? target_path puts "Restoring #{ENV['RACK_ENV']} database from #{target_path}" # Ensure we're starting from a clean DB. system "dropdb trunk_cocoapods_org_test" system "createdb trunk_cocoapods_org_test" # Restore the DB. command = "pg_restore --no-privileges --clean --no-acl --no-owner -h localhost -d trunk_cocoapods_org_test #{target_path}" puts "Executing:" puts command puts result = system command if result puts "Database #{ENV['RACK_ENV']} restored from #{target_path}" else warn "Database #{ENV['RACK_ENV']} restored from #{target_path} with some errors." # exit 1 end end
ruby
def seed_from_dump id target_path = File.expand_path("../../fixtures/trunk-#{id}.dump", __FILE__) raise "Dump #{id} could not be found." unless File.exists? target_path puts "Restoring #{ENV['RACK_ENV']} database from #{target_path}" # Ensure we're starting from a clean DB. system "dropdb trunk_cocoapods_org_test" system "createdb trunk_cocoapods_org_test" # Restore the DB. command = "pg_restore --no-privileges --clean --no-acl --no-owner -h localhost -d trunk_cocoapods_org_test #{target_path}" puts "Executing:" puts command puts result = system command if result puts "Database #{ENV['RACK_ENV']} restored from #{target_path}" else warn "Database #{ENV['RACK_ENV']} restored from #{target_path} with some errors." # exit 1 end end
[ "def", "seed_from_dump", "id", "target_path", "=", "File", ".", "expand_path", "(", "\"../../fixtures/trunk-#{id}.dump\"", ",", "__FILE__", ")", "raise", "\"Dump #{id} could not be found.\"", "unless", "File", ".", "exists?", "target_path", "puts", "\"Restoring #{ENV['RACK_ENV']} database from #{target_path}\"", "system", "\"dropdb trunk_cocoapods_org_test\"", "system", "\"createdb trunk_cocoapods_org_test\"", "command", "=", "\"pg_restore --no-privileges --clean --no-acl --no-owner -h localhost -d trunk_cocoapods_org_test #{target_path}\"", "puts", "\"Executing:\"", "puts", "command", "puts", "result", "=", "system", "command", "if", "result", "puts", "\"Database #{ENV['RACK_ENV']} restored from #{target_path}\"", "else", "warn", "\"Database #{ENV['RACK_ENV']} restored from #{target_path} with some errors.\"", "end", "end" ]
Seed the database from a downloaded dump.
[ "Seed", "the", "database", "from", "a", "downloaded", "dump", "." ]
dd2b1b2b484cc5636bf16ecb4fc189c728dbb23e
https://github.com/CocoaPods/Humus/blob/dd2b1b2b484cc5636bf16ecb4fc189c728dbb23e/lib/snapshots.rb#L43-L65
train
CocoaPods/Humus
lib/snapshots.rb
Humus.Snapshots.dump_prod
def dump_prod id target_path = File.expand_path("../../fixtures/trunk-#{id}.dump", __FILE__) puts "Dumping production database from Heroku (works only if you have access to the database)" command = "curl -o #{target_path} \`heroku pg:backups public-url #{id} -a cocoapods-trunk-service\`" puts "Executing command:" puts command result = system command if result puts "Production database snapshot #{id} dumped into #{target_path}" else raise "Could not dump #{id} from production database." end end
ruby
def dump_prod id target_path = File.expand_path("../../fixtures/trunk-#{id}.dump", __FILE__) puts "Dumping production database from Heroku (works only if you have access to the database)" command = "curl -o #{target_path} \`heroku pg:backups public-url #{id} -a cocoapods-trunk-service\`" puts "Executing command:" puts command result = system command if result puts "Production database snapshot #{id} dumped into #{target_path}" else raise "Could not dump #{id} from production database." end end
[ "def", "dump_prod", "id", "target_path", "=", "File", ".", "expand_path", "(", "\"../../fixtures/trunk-#{id}.dump\"", ",", "__FILE__", ")", "puts", "\"Dumping production database from Heroku (works only if you have access to the database)\"", "command", "=", "\"curl -o #{target_path} \\`heroku pg:backups public-url #{id} -a cocoapods-trunk-service\\`\"", "puts", "\"Executing command:\"", "puts", "command", "result", "=", "system", "command", "if", "result", "puts", "\"Production database snapshot #{id} dumped into #{target_path}\"", "else", "raise", "\"Could not dump #{id} from production database.\"", "end", "end" ]
Dump the production DB.
[ "Dump", "the", "production", "DB", "." ]
dd2b1b2b484cc5636bf16ecb4fc189c728dbb23e
https://github.com/CocoaPods/Humus/blob/dd2b1b2b484cc5636bf16ecb4fc189c728dbb23e/lib/snapshots.rb#L69-L81
train
arvicco/win
lib/win/library.rb
Win.Library.try_function
def try_function(name, params, returns, options={}, &def_block) begin function name, params, returns, options, &def_block rescue Win::Errors::NotFoundError "This platform does not support function #{name}" end end
ruby
def try_function(name, params, returns, options={}, &def_block) begin function name, params, returns, options, &def_block rescue Win::Errors::NotFoundError "This platform does not support function #{name}" end end
[ "def", "try_function", "(", "name", ",", "params", ",", "returns", ",", "options", "=", "{", "}", ",", "&", "def_block", ")", "begin", "function", "name", ",", "params", ",", "returns", ",", "options", ",", "&", "def_block", "rescue", "Win", "::", "Errors", "::", "NotFoundError", "\"This platform does not support function #{name}\"", "end", "end" ]
Try to define platform-specific function, rescue error, return message
[ "Try", "to", "define", "platform", "-", "specific", "function", "rescue", "error", "return", "message" ]
835a998100b5584a9b2b5c5888567c948929f36a
https://github.com/arvicco/win/blob/835a998100b5584a9b2b5c5888567c948929f36a/lib/win/library.rb#L299-L305
train
arvicco/win
lib/win/library.rb
Win.Library.define_api
def define_api(name, camel_name, effective_names, params, returns, options) params, returns = generate_signature(params.dup, returns) ffi_lib *(ffi_libraries.map(&:name) << options[:dll]) if options[:dll] libs = ffi_libraries.map(&:name) alternative = options.delete(:alternative) # Function may have alternative signature effective_name = if alternative alt_params, alt_returns, condition = generate_signature(*alternative) api = function name, params, returns, options.merge( camel_only: true, camel_name: "#{camel_name}Original") alt_api = function name, alt_params, alt_returns, options.merge( camel_only: true, camel_name: "#{camel_name}Alternative") define_method camel_name do |*args| (condition[*args] ? alt_api : api).call(*args) end module_function camel_name public camel_name api.effective_name else effective_names.inject(nil) do |func, effective_name| func || begin # Try to attach basic CamelCase method via FFI attach_function(camel_name, effective_name, params.dup, returns) effective_name rescue FFI::NotFoundError nil end end end raise Win::Errors::NotFoundError.new(name, libs) unless effective_name # Create API object that holds information about defined and effective function names, params, etc. # This object is further used by enhanced snake_case method to reflect on underlying API and # intelligently call it. API.new(namespace, camel_name, effective_name, params, returns, libs) end
ruby
def define_api(name, camel_name, effective_names, params, returns, options) params, returns = generate_signature(params.dup, returns) ffi_lib *(ffi_libraries.map(&:name) << options[:dll]) if options[:dll] libs = ffi_libraries.map(&:name) alternative = options.delete(:alternative) # Function may have alternative signature effective_name = if alternative alt_params, alt_returns, condition = generate_signature(*alternative) api = function name, params, returns, options.merge( camel_only: true, camel_name: "#{camel_name}Original") alt_api = function name, alt_params, alt_returns, options.merge( camel_only: true, camel_name: "#{camel_name}Alternative") define_method camel_name do |*args| (condition[*args] ? alt_api : api).call(*args) end module_function camel_name public camel_name api.effective_name else effective_names.inject(nil) do |func, effective_name| func || begin # Try to attach basic CamelCase method via FFI attach_function(camel_name, effective_name, params.dup, returns) effective_name rescue FFI::NotFoundError nil end end end raise Win::Errors::NotFoundError.new(name, libs) unless effective_name # Create API object that holds information about defined and effective function names, params, etc. # This object is further used by enhanced snake_case method to reflect on underlying API and # intelligently call it. API.new(namespace, camel_name, effective_name, params, returns, libs) end
[ "def", "define_api", "(", "name", ",", "camel_name", ",", "effective_names", ",", "params", ",", "returns", ",", "options", ")", "params", ",", "returns", "=", "generate_signature", "(", "params", ".", "dup", ",", "returns", ")", "ffi_lib", "*", "(", "ffi_libraries", ".", "map", "(", "&", ":name", ")", "<<", "options", "[", ":dll", "]", ")", "if", "options", "[", ":dll", "]", "libs", "=", "ffi_libraries", ".", "map", "(", "&", ":name", ")", "alternative", "=", "options", ".", "delete", "(", ":alternative", ")", "effective_name", "=", "if", "alternative", "alt_params", ",", "alt_returns", ",", "condition", "=", "generate_signature", "(", "*", "alternative", ")", "api", "=", "function", "name", ",", "params", ",", "returns", ",", "options", ".", "merge", "(", "camel_only", ":", "true", ",", "camel_name", ":", "\"#{camel_name}Original\"", ")", "alt_api", "=", "function", "name", ",", "alt_params", ",", "alt_returns", ",", "options", ".", "merge", "(", "camel_only", ":", "true", ",", "camel_name", ":", "\"#{camel_name}Alternative\"", ")", "define_method", "camel_name", "do", "|", "*", "args", "|", "(", "condition", "[", "*", "args", "]", "?", "alt_api", ":", "api", ")", ".", "call", "(", "*", "args", ")", "end", "module_function", "camel_name", "public", "camel_name", "api", ".", "effective_name", "else", "effective_names", ".", "inject", "(", "nil", ")", "do", "|", "func", ",", "effective_name", "|", "func", "||", "begin", "attach_function", "(", "camel_name", ",", "effective_name", ",", "params", ".", "dup", ",", "returns", ")", "effective_name", "rescue", "FFI", "::", "NotFoundError", "nil", "end", "end", "end", "raise", "Win", "::", "Errors", "::", "NotFoundError", ".", "new", "(", "name", ",", "libs", ")", "unless", "effective_name", "API", ".", "new", "(", "namespace", ",", "camel_name", ",", "effective_name", ",", "params", ",", "returns", ",", "libs", ")", "end" ]
Defines CamelCase method calling Win32 API function, and associated API object
[ "Defines", "CamelCase", "method", "calling", "Win32", "API", "function", "and", "associated", "API", "object" ]
835a998100b5584a9b2b5c5888567c948929f36a
https://github.com/arvicco/win/blob/835a998100b5584a9b2b5c5888567c948929f36a/lib/win/library.rb#L309-L348
train
zdennis/yap-shell-core
lib/yap/shell/evaluation.rb
Yap::Shell.Evaluation.recursively_find_and_replace_command_substitutions
def recursively_find_and_replace_command_substitutions(input) input = input.dup Parser.each_command_substitution_for(input) do |substitution_result, start_position, end_position| debug_log "found command substitution at position=#{(start_position..end_position)} #{substitution_result.inspect}" result = recursively_find_and_replace_command_substitutions(substitution_result.str) position = substitution_result.position ast = Parser.parse(result) with_standard_streams do |stdin, stdout, stderr| r,w = IO.pipe @stdout = w ast.accept(self) output = r.read.chomp # Treat consecutive newlines in output as a single space output = output.gsub(/\n+/, ' ') # Double quote the output and escape any double quotes already # existing output = %|"#{output.gsub(/"/, '\\"')}"| # Put thd output back into the original input debug_log "replacing command substitution at position=#{(position.min...position.max)} with #{output.inspect}" input[position.min...position.max] = output end end input end
ruby
def recursively_find_and_replace_command_substitutions(input) input = input.dup Parser.each_command_substitution_for(input) do |substitution_result, start_position, end_position| debug_log "found command substitution at position=#{(start_position..end_position)} #{substitution_result.inspect}" result = recursively_find_and_replace_command_substitutions(substitution_result.str) position = substitution_result.position ast = Parser.parse(result) with_standard_streams do |stdin, stdout, stderr| r,w = IO.pipe @stdout = w ast.accept(self) output = r.read.chomp # Treat consecutive newlines in output as a single space output = output.gsub(/\n+/, ' ') # Double quote the output and escape any double quotes already # existing output = %|"#{output.gsub(/"/, '\\"')}"| # Put thd output back into the original input debug_log "replacing command substitution at position=#{(position.min...position.max)} with #{output.inspect}" input[position.min...position.max] = output end end input end
[ "def", "recursively_find_and_replace_command_substitutions", "(", "input", ")", "input", "=", "input", ".", "dup", "Parser", ".", "each_command_substitution_for", "(", "input", ")", "do", "|", "substitution_result", ",", "start_position", ",", "end_position", "|", "debug_log", "\"found command substitution at position=#{(start_position..end_position)} #{substitution_result.inspect}\"", "result", "=", "recursively_find_and_replace_command_substitutions", "(", "substitution_result", ".", "str", ")", "position", "=", "substitution_result", ".", "position", "ast", "=", "Parser", ".", "parse", "(", "result", ")", "with_standard_streams", "do", "|", "stdin", ",", "stdout", ",", "stderr", "|", "r", ",", "w", "=", "IO", ".", "pipe", "@stdout", "=", "w", "ast", ".", "accept", "(", "self", ")", "output", "=", "r", ".", "read", ".", "chomp", "output", "=", "output", ".", "gsub", "(", "/", "\\n", "/", ",", "' '", ")", "output", "=", "%|\"#{output.gsub(/\"/, '\\\\\"')}\"|", "debug_log", "\"replacing command substitution at position=#{(position.min...position.max)} with #{output.inspect}\"", "input", "[", "position", ".", "min", "...", "position", ".", "max", "]", "=", "output", "end", "end", "input", "end" ]
+recursively_find_and_replace_command_substitutions+ is responsible for recursively finding and expanding command substitutions, in a depth first manner.
[ "+", "recursively_find_and_replace_command_substitutions", "+", "is", "responsible", "for", "recursively", "finding", "and", "expanding", "command", "substitutions", "in", "a", "depth", "first", "manner", "." ]
37f1c871c492215cbfad85c228ac19adb39d940e
https://github.com/zdennis/yap-shell-core/blob/37f1c871c492215cbfad85c228ac19adb39d940e/lib/yap/shell/evaluation.rb#L46-L73
train
zdennis/yap-shell-core
lib/yap/shell/evaluation.rb
Yap::Shell.Evaluation.visit_CommandNode
def visit_CommandNode(node) debug_visit(node) @aliases_expanded ||= [] @command_node_args_stack ||= [] with_standard_streams do |stdin, stdout, stderr| args = process_ArgumentNodes(node.args) if !node.literal? && !@aliases_expanded.include?(node.command) && Aliases.instance.has_key?(node.command) _alias=Aliases.instance.fetch_alias(node.command) @suppress_events = true @command_node_args_stack << args ast = Parser.parse(_alias) @aliases_expanded.push(node.command) ast.accept(self) @aliases_expanded.pop @suppress_events = false else cmd2execute = variable_expand(node.command) final_args = (args + @command_node_args_stack).flatten.map(&:shellescape) expanded_args = final_args command = CommandFactory.build_command_for( world: world, command: cmd2execute, args: expanded_args, heredoc: (node.heredoc && node.heredoc.value), internally_evaluate: node.internally_evaluate?, line: @input) @stdin, @stdout, @stderr = stream_redirections_for(node) set_last_result @blk.call command, @stdin, @stdout, @stderr, pipeline_stack.empty? @command_node_args_stack.clear end end end
ruby
def visit_CommandNode(node) debug_visit(node) @aliases_expanded ||= [] @command_node_args_stack ||= [] with_standard_streams do |stdin, stdout, stderr| args = process_ArgumentNodes(node.args) if !node.literal? && !@aliases_expanded.include?(node.command) && Aliases.instance.has_key?(node.command) _alias=Aliases.instance.fetch_alias(node.command) @suppress_events = true @command_node_args_stack << args ast = Parser.parse(_alias) @aliases_expanded.push(node.command) ast.accept(self) @aliases_expanded.pop @suppress_events = false else cmd2execute = variable_expand(node.command) final_args = (args + @command_node_args_stack).flatten.map(&:shellescape) expanded_args = final_args command = CommandFactory.build_command_for( world: world, command: cmd2execute, args: expanded_args, heredoc: (node.heredoc && node.heredoc.value), internally_evaluate: node.internally_evaluate?, line: @input) @stdin, @stdout, @stderr = stream_redirections_for(node) set_last_result @blk.call command, @stdin, @stdout, @stderr, pipeline_stack.empty? @command_node_args_stack.clear end end end
[ "def", "visit_CommandNode", "(", "node", ")", "debug_visit", "(", "node", ")", "@aliases_expanded", "||=", "[", "]", "@command_node_args_stack", "||=", "[", "]", "with_standard_streams", "do", "|", "stdin", ",", "stdout", ",", "stderr", "|", "args", "=", "process_ArgumentNodes", "(", "node", ".", "args", ")", "if", "!", "node", ".", "literal?", "&&", "!", "@aliases_expanded", ".", "include?", "(", "node", ".", "command", ")", "&&", "Aliases", ".", "instance", ".", "has_key?", "(", "node", ".", "command", ")", "_alias", "=", "Aliases", ".", "instance", ".", "fetch_alias", "(", "node", ".", "command", ")", "@suppress_events", "=", "true", "@command_node_args_stack", "<<", "args", "ast", "=", "Parser", ".", "parse", "(", "_alias", ")", "@aliases_expanded", ".", "push", "(", "node", ".", "command", ")", "ast", ".", "accept", "(", "self", ")", "@aliases_expanded", ".", "pop", "@suppress_events", "=", "false", "else", "cmd2execute", "=", "variable_expand", "(", "node", ".", "command", ")", "final_args", "=", "(", "args", "+", "@command_node_args_stack", ")", ".", "flatten", ".", "map", "(", "&", ":shellescape", ")", "expanded_args", "=", "final_args", "command", "=", "CommandFactory", ".", "build_command_for", "(", "world", ":", "world", ",", "command", ":", "cmd2execute", ",", "args", ":", "expanded_args", ",", "heredoc", ":", "(", "node", ".", "heredoc", "&&", "node", ".", "heredoc", ".", "value", ")", ",", "internally_evaluate", ":", "node", ".", "internally_evaluate?", ",", "line", ":", "@input", ")", "@stdin", ",", "@stdout", ",", "@stderr", "=", "stream_redirections_for", "(", "node", ")", "set_last_result", "@blk", ".", "call", "command", ",", "@stdin", ",", "@stdout", ",", "@stderr", ",", "pipeline_stack", ".", "empty?", "@command_node_args_stack", ".", "clear", "end", "end", "end" ]
VISITOR METHODS FOR AST TREE WALKING
[ "VISITOR", "METHODS", "FOR", "AST", "TREE", "WALKING" ]
37f1c871c492215cbfad85c228ac19adb39d940e
https://github.com/zdennis/yap-shell-core/blob/37f1c871c492215cbfad85c228ac19adb39d940e/lib/yap/shell/evaluation.rb#L82-L113
train
fwal/danger-jazzy
lib/jazzy/plugin.rb
Danger.DangerJazzy.undocumented
def undocumented(scope = :modified) return [] unless scope != :ignore && File.exist?(undocumented_path) @undocumented = { modified: [], all: [] } if @undocumented.nil? load_undocumented(scope) if @undocumented[scope].empty? @undocumented[scope] end
ruby
def undocumented(scope = :modified) return [] unless scope != :ignore && File.exist?(undocumented_path) @undocumented = { modified: [], all: [] } if @undocumented.nil? load_undocumented(scope) if @undocumented[scope].empty? @undocumented[scope] end
[ "def", "undocumented", "(", "scope", "=", ":modified", ")", "return", "[", "]", "unless", "scope", "!=", ":ignore", "&&", "File", ".", "exist?", "(", "undocumented_path", ")", "@undocumented", "=", "{", "modified", ":", "[", "]", ",", "all", ":", "[", "]", "}", "if", "@undocumented", ".", "nil?", "load_undocumented", "(", "scope", ")", "if", "@undocumented", "[", "scope", "]", ".", "empty?", "@undocumented", "[", "scope", "]", "end" ]
Returns a list of undocumented symbols in the current diff. Available scopes: * `modified` * `all` @param [Key] scope @return [Array of symbol]
[ "Returns", "a", "list", "of", "undocumented", "symbols", "in", "the", "current", "diff", "." ]
a125fa61977621a07762c50fc44fb62942c3df68
https://github.com/fwal/danger-jazzy/blob/a125fa61977621a07762c50fc44fb62942c3df68/lib/jazzy/plugin.rb#L81-L86
train
kukareka/spree_liqpay
app/controllers/spree/liqpay_status_controller.rb
Spree.LiqpayStatusController.update
def update @payment_method = PaymentMethod.find params[:payment_method_id] data = JSON.parse Base64.strict_decode64 params[:data] render text: "Bad signature\n", status: 401 and return unless @payment_method.check_signature params[:data], params[:signature] @order = Order.find data['order_id'] raise ArgumentError unless @order.payments.completed.empty? && data['currency'] == @order.currency && BigDecimal(data['amount']) == @order.total && data['type'] == 'buy' && (data['status'] == 'success' || (@payment_method.preferred_test_mode && data['status'] == 'sandbox')) payment = @order.payments.create amount: @order.total, payment_method: @payment_method payment.complete! render text: "Thank you.\n" end
ruby
def update @payment_method = PaymentMethod.find params[:payment_method_id] data = JSON.parse Base64.strict_decode64 params[:data] render text: "Bad signature\n", status: 401 and return unless @payment_method.check_signature params[:data], params[:signature] @order = Order.find data['order_id'] raise ArgumentError unless @order.payments.completed.empty? && data['currency'] == @order.currency && BigDecimal(data['amount']) == @order.total && data['type'] == 'buy' && (data['status'] == 'success' || (@payment_method.preferred_test_mode && data['status'] == 'sandbox')) payment = @order.payments.create amount: @order.total, payment_method: @payment_method payment.complete! render text: "Thank you.\n" end
[ "def", "update", "@payment_method", "=", "PaymentMethod", ".", "find", "params", "[", ":payment_method_id", "]", "data", "=", "JSON", ".", "parse", "Base64", ".", "strict_decode64", "params", "[", ":data", "]", "render", "text", ":", "\"Bad signature\\n\"", ",", "status", ":", "401", "and", "return", "unless", "@payment_method", ".", "check_signature", "params", "[", ":data", "]", ",", "params", "[", ":signature", "]", "@order", "=", "Order", ".", "find", "data", "[", "'order_id'", "]", "raise", "ArgumentError", "unless", "@order", ".", "payments", ".", "completed", ".", "empty?", "&&", "data", "[", "'currency'", "]", "==", "@order", ".", "currency", "&&", "BigDecimal", "(", "data", "[", "'amount'", "]", ")", "==", "@order", ".", "total", "&&", "data", "[", "'type'", "]", "==", "'buy'", "&&", "(", "data", "[", "'status'", "]", "==", "'success'", "||", "(", "@payment_method", ".", "preferred_test_mode", "&&", "data", "[", "'status'", "]", "==", "'sandbox'", ")", ")", "payment", "=", "@order", ".", "payments", ".", "create", "amount", ":", "@order", ".", "total", ",", "payment_method", ":", "@payment_method", "payment", ".", "complete!", "render", "text", ":", "\"Thank you.\\n\"", "end" ]
callbacks from Liqpay server
[ "callbacks", "from", "Liqpay", "server" ]
996ef2908adbc512571e03dc148613f59fc05766
https://github.com/kukareka/spree_liqpay/blob/996ef2908adbc512571e03dc148613f59fc05766/app/controllers/spree/liqpay_status_controller.rb#L7-L23
train
wvanbergen/kazoo
lib/kazoo/cluster.rb
Kazoo.Cluster.brokers
def brokers @brokers_mutex.synchronize do @brokers ||= begin brokers = zk.get_children(path: "/brokers/ids") if brokers.fetch(:rc) != Zookeeper::Constants::ZOK raise NoClusterRegistered, "No Kafka cluster registered on this Zookeeper location." end result, mutex = {}, Mutex.new threads = brokers.fetch(:children).map do |id| Thread.new do Thread.abort_on_exception = true broker_info = zk.get(path: "/brokers/ids/#{id}") raise Kazoo::Error, "Failed to retrieve broker info. Error code: #{broker_info.fetch(:rc)}" unless broker_info.fetch(:rc) == Zookeeper::Constants::ZOK broker = Kazoo::Broker.from_json(self, id, JSON.parse(broker_info.fetch(:data))) mutex.synchronize { result[id.to_i] = broker } end end threads.each(&:join) result end end end
ruby
def brokers @brokers_mutex.synchronize do @brokers ||= begin brokers = zk.get_children(path: "/brokers/ids") if brokers.fetch(:rc) != Zookeeper::Constants::ZOK raise NoClusterRegistered, "No Kafka cluster registered on this Zookeeper location." end result, mutex = {}, Mutex.new threads = brokers.fetch(:children).map do |id| Thread.new do Thread.abort_on_exception = true broker_info = zk.get(path: "/brokers/ids/#{id}") raise Kazoo::Error, "Failed to retrieve broker info. Error code: #{broker_info.fetch(:rc)}" unless broker_info.fetch(:rc) == Zookeeper::Constants::ZOK broker = Kazoo::Broker.from_json(self, id, JSON.parse(broker_info.fetch(:data))) mutex.synchronize { result[id.to_i] = broker } end end threads.each(&:join) result end end end
[ "def", "brokers", "@brokers_mutex", ".", "synchronize", "do", "@brokers", "||=", "begin", "brokers", "=", "zk", ".", "get_children", "(", "path", ":", "\"/brokers/ids\"", ")", "if", "brokers", ".", "fetch", "(", ":rc", ")", "!=", "Zookeeper", "::", "Constants", "::", "ZOK", "raise", "NoClusterRegistered", ",", "\"No Kafka cluster registered on this Zookeeper location.\"", "end", "result", ",", "mutex", "=", "{", "}", ",", "Mutex", ".", "new", "threads", "=", "brokers", ".", "fetch", "(", ":children", ")", ".", "map", "do", "|", "id", "|", "Thread", ".", "new", "do", "Thread", ".", "abort_on_exception", "=", "true", "broker_info", "=", "zk", ".", "get", "(", "path", ":", "\"/brokers/ids/#{id}\"", ")", "raise", "Kazoo", "::", "Error", ",", "\"Failed to retrieve broker info. Error code: #{broker_info.fetch(:rc)}\"", "unless", "broker_info", ".", "fetch", "(", ":rc", ")", "==", "Zookeeper", "::", "Constants", "::", "ZOK", "broker", "=", "Kazoo", "::", "Broker", ".", "from_json", "(", "self", ",", "id", ",", "JSON", ".", "parse", "(", "broker_info", ".", "fetch", "(", ":data", ")", ")", ")", "mutex", ".", "synchronize", "{", "result", "[", "id", ".", "to_i", "]", "=", "broker", "}", "end", "end", "threads", ".", "each", "(", "&", ":join", ")", "result", "end", "end", "end" ]
Returns a hash of all the brokers in the
[ "Returns", "a", "hash", "of", "all", "the", "brokers", "in", "the" ]
54a73612ef4b815fad37ba660eb47353e26165f1
https://github.com/wvanbergen/kazoo/blob/54a73612ef4b815fad37ba660eb47353e26165f1/lib/kazoo/cluster.rb#L22-L46
train
wvanbergen/kazoo
lib/kazoo/cluster.rb
Kazoo.Cluster.consumergroups
def consumergroups @consumergroups ||= begin consumers = zk.get_children(path: "/consumers") consumers.fetch(:children).map { |name| Kazoo::Consumergroup.new(self, name) } end end
ruby
def consumergroups @consumergroups ||= begin consumers = zk.get_children(path: "/consumers") consumers.fetch(:children).map { |name| Kazoo::Consumergroup.new(self, name) } end end
[ "def", "consumergroups", "@consumergroups", "||=", "begin", "consumers", "=", "zk", ".", "get_children", "(", "path", ":", "\"/consumers\"", ")", "consumers", ".", "fetch", "(", ":children", ")", ".", "map", "{", "|", "name", "|", "Kazoo", "::", "Consumergroup", ".", "new", "(", "self", ",", "name", ")", "}", "end", "end" ]
Returns a list of consumer groups that are registered against the Kafka cluster.
[ "Returns", "a", "list", "of", "consumer", "groups", "that", "are", "registered", "against", "the", "Kafka", "cluster", "." ]
54a73612ef4b815fad37ba660eb47353e26165f1
https://github.com/wvanbergen/kazoo/blob/54a73612ef4b815fad37ba660eb47353e26165f1/lib/kazoo/cluster.rb#L49-L54
train
wvanbergen/kazoo
lib/kazoo/cluster.rb
Kazoo.Cluster.topics
def topics(preload: Kazoo::Topic::DEFAULT_PRELOAD_METHODS) @topics_mutex.synchronize do @topics ||= begin topics = zk.get_children(path: "/brokers/topics") raise Kazoo::Error, "Failed to list topics. Error code: #{topics.fetch(:rc)}" unless topics.fetch(:rc) == Zookeeper::Constants::ZOK preload_topics_from_names(topics.fetch(:children), preload: preload) end end end
ruby
def topics(preload: Kazoo::Topic::DEFAULT_PRELOAD_METHODS) @topics_mutex.synchronize do @topics ||= begin topics = zk.get_children(path: "/brokers/topics") raise Kazoo::Error, "Failed to list topics. Error code: #{topics.fetch(:rc)}" unless topics.fetch(:rc) == Zookeeper::Constants::ZOK preload_topics_from_names(topics.fetch(:children), preload: preload) end end end
[ "def", "topics", "(", "preload", ":", "Kazoo", "::", "Topic", "::", "DEFAULT_PRELOAD_METHODS", ")", "@topics_mutex", ".", "synchronize", "do", "@topics", "||=", "begin", "topics", "=", "zk", ".", "get_children", "(", "path", ":", "\"/brokers/topics\"", ")", "raise", "Kazoo", "::", "Error", ",", "\"Failed to list topics. Error code: #{topics.fetch(:rc)}\"", "unless", "topics", ".", "fetch", "(", ":rc", ")", "==", "Zookeeper", "::", "Constants", "::", "ZOK", "preload_topics_from_names", "(", "topics", ".", "fetch", "(", ":children", ")", ",", "preload", ":", "preload", ")", "end", "end", "end" ]
Returns a hash of all the topics in the Kafka cluster, indexed by the topic name.
[ "Returns", "a", "hash", "of", "all", "the", "topics", "in", "the", "Kafka", "cluster", "indexed", "by", "the", "topic", "name", "." ]
54a73612ef4b815fad37ba660eb47353e26165f1
https://github.com/wvanbergen/kazoo/blob/54a73612ef4b815fad37ba660eb47353e26165f1/lib/kazoo/cluster.rb#L65-L73
train
wvanbergen/kazoo
lib/kazoo/cluster.rb
Kazoo.Cluster.create_topic
def create_topic(name, partitions: nil, replication_factor: nil, config: nil) raise ArgumentError, "partitions must be a positive integer" if Integer(partitions) <= 0 raise ArgumentError, "replication_factor must be a positive integer" if Integer(replication_factor) <= 0 Kazoo::Topic.create(self, name, partitions: Integer(partitions), replication_factor: Integer(replication_factor), config: config) end
ruby
def create_topic(name, partitions: nil, replication_factor: nil, config: nil) raise ArgumentError, "partitions must be a positive integer" if Integer(partitions) <= 0 raise ArgumentError, "replication_factor must be a positive integer" if Integer(replication_factor) <= 0 Kazoo::Topic.create(self, name, partitions: Integer(partitions), replication_factor: Integer(replication_factor), config: config) end
[ "def", "create_topic", "(", "name", ",", "partitions", ":", "nil", ",", "replication_factor", ":", "nil", ",", "config", ":", "nil", ")", "raise", "ArgumentError", ",", "\"partitions must be a positive integer\"", "if", "Integer", "(", "partitions", ")", "<=", "0", "raise", "ArgumentError", ",", "\"replication_factor must be a positive integer\"", "if", "Integer", "(", "replication_factor", ")", "<=", "0", "Kazoo", "::", "Topic", ".", "create", "(", "self", ",", "name", ",", "partitions", ":", "Integer", "(", "partitions", ")", ",", "replication_factor", ":", "Integer", "(", "replication_factor", ")", ",", "config", ":", "config", ")", "end" ]
Creates a topic on the Kafka cluster, with the provided number of partitions and replication factor.
[ "Creates", "a", "topic", "on", "the", "Kafka", "cluster", "with", "the", "provided", "number", "of", "partitions", "and", "replication", "factor", "." ]
54a73612ef4b815fad37ba660eb47353e26165f1
https://github.com/wvanbergen/kazoo/blob/54a73612ef4b815fad37ba660eb47353e26165f1/lib/kazoo/cluster.rb#L82-L87
train
wvanbergen/kazoo
lib/kazoo/cluster.rb
Kazoo.Cluster.preferred_leader_election
def preferred_leader_election(partitions: nil) partitions = self.partitions if partitions.nil? result = zk.create(path: "/admin/preferred_replica_election", data: JSON.generate(version: 1, partitions: partitions)) case result.fetch(:rc) when Zookeeper::Constants::ZOK return true when Zookeeper::Constants::ZNODEEXISTS raise Kazoo::Error, "Another preferred leader election is still in progress" else raise Kazoo::Error, "Failed to start preferred leadership election. Result code: #{result.fetch(:rc)}" end end
ruby
def preferred_leader_election(partitions: nil) partitions = self.partitions if partitions.nil? result = zk.create(path: "/admin/preferred_replica_election", data: JSON.generate(version: 1, partitions: partitions)) case result.fetch(:rc) when Zookeeper::Constants::ZOK return true when Zookeeper::Constants::ZNODEEXISTS raise Kazoo::Error, "Another preferred leader election is still in progress" else raise Kazoo::Error, "Failed to start preferred leadership election. Result code: #{result.fetch(:rc)}" end end
[ "def", "preferred_leader_election", "(", "partitions", ":", "nil", ")", "partitions", "=", "self", ".", "partitions", "if", "partitions", ".", "nil?", "result", "=", "zk", ".", "create", "(", "path", ":", "\"/admin/preferred_replica_election\"", ",", "data", ":", "JSON", ".", "generate", "(", "version", ":", "1", ",", "partitions", ":", "partitions", ")", ")", "case", "result", ".", "fetch", "(", ":rc", ")", "when", "Zookeeper", "::", "Constants", "::", "ZOK", "return", "true", "when", "Zookeeper", "::", "Constants", "::", "ZNODEEXISTS", "raise", "Kazoo", "::", "Error", ",", "\"Another preferred leader election is still in progress\"", "else", "raise", "Kazoo", "::", "Error", ",", "\"Failed to start preferred leadership election. Result code: #{result.fetch(:rc)}\"", "end", "end" ]
Triggers a preferred leader elections for the provided list of partitions. If no list of partitions is provided, the preferred leader will be elected for all partitions in the cluster.
[ "Triggers", "a", "preferred", "leader", "elections", "for", "the", "provided", "list", "of", "partitions", ".", "If", "no", "list", "of", "partitions", "is", "provided", "the", "preferred", "leader", "will", "be", "elected", "for", "all", "partitions", "in", "the", "cluster", "." ]
54a73612ef4b815fad37ba660eb47353e26165f1
https://github.com/wvanbergen/kazoo/blob/54a73612ef4b815fad37ba660eb47353e26165f1/lib/kazoo/cluster.rb#L107-L118
train
wvanbergen/kazoo
lib/kazoo/cluster.rb
Kazoo.Cluster.recursive_create
def recursive_create(path: nil) raise ArgumentError, "path is a required argument" if path.nil? result = zk.stat(path: path) case result.fetch(:rc) when Zookeeper::Constants::ZOK return when Zookeeper::Constants::ZNONODE recursive_create(path: File.dirname(path)) result = zk.create(path: path) case result.fetch(:rc) when Zookeeper::Constants::ZOK, Zookeeper::Constants::ZNODEEXISTS return else raise Kazoo::Error, "Failed to create node #{path}. Result code: #{result.fetch(:rc)}" end else raise Kazoo::Error, "Failed to create node #{path}. Result code: #{result.fetch(:rc)}" end end
ruby
def recursive_create(path: nil) raise ArgumentError, "path is a required argument" if path.nil? result = zk.stat(path: path) case result.fetch(:rc) when Zookeeper::Constants::ZOK return when Zookeeper::Constants::ZNONODE recursive_create(path: File.dirname(path)) result = zk.create(path: path) case result.fetch(:rc) when Zookeeper::Constants::ZOK, Zookeeper::Constants::ZNODEEXISTS return else raise Kazoo::Error, "Failed to create node #{path}. Result code: #{result.fetch(:rc)}" end else raise Kazoo::Error, "Failed to create node #{path}. Result code: #{result.fetch(:rc)}" end end
[ "def", "recursive_create", "(", "path", ":", "nil", ")", "raise", "ArgumentError", ",", "\"path is a required argument\"", "if", "path", ".", "nil?", "result", "=", "zk", ".", "stat", "(", "path", ":", "path", ")", "case", "result", ".", "fetch", "(", ":rc", ")", "when", "Zookeeper", "::", "Constants", "::", "ZOK", "return", "when", "Zookeeper", "::", "Constants", "::", "ZNONODE", "recursive_create", "(", "path", ":", "File", ".", "dirname", "(", "path", ")", ")", "result", "=", "zk", ".", "create", "(", "path", ":", "path", ")", "case", "result", ".", "fetch", "(", ":rc", ")", "when", "Zookeeper", "::", "Constants", "::", "ZOK", ",", "Zookeeper", "::", "Constants", "::", "ZNODEEXISTS", "return", "else", "raise", "Kazoo", "::", "Error", ",", "\"Failed to create node #{path}. Result code: #{result.fetch(:rc)}\"", "end", "else", "raise", "Kazoo", "::", "Error", ",", "\"Failed to create node #{path}. Result code: #{result.fetch(:rc)}\"", "end", "end" ]
Recursively creates a node in Zookeeper, by recusrively trying to create its parent if it doesn not yet exist.
[ "Recursively", "creates", "a", "node", "in", "Zookeeper", "by", "recusrively", "trying", "to", "create", "its", "parent", "if", "it", "doesn", "not", "yet", "exist", "." ]
54a73612ef4b815fad37ba660eb47353e26165f1
https://github.com/wvanbergen/kazoo/blob/54a73612ef4b815fad37ba660eb47353e26165f1/lib/kazoo/cluster.rb#L131-L151
train
wvanbergen/kazoo
lib/kazoo/cluster.rb
Kazoo.Cluster.recursive_delete
def recursive_delete(path: nil) raise ArgumentError, "path is a required argument" if path.nil? result = zk.get_children(path: path) raise Kazoo::Error, "Failed to list children of #{path} to delete them. Result code: #{result.fetch(:rc)}" if result.fetch(:rc) != Zookeeper::Constants::ZOK threads = result.fetch(:children).map do |name| Thread.new do Thread.abort_on_exception = true recursive_delete(path: File.join(path, name)) end end threads.each(&:join) result = zk.delete(path: path) raise Kazoo::Error, "Failed to delete node #{path}. Result code: #{result.fetch(:rc)}" if result.fetch(:rc) != Zookeeper::Constants::ZOK end
ruby
def recursive_delete(path: nil) raise ArgumentError, "path is a required argument" if path.nil? result = zk.get_children(path: path) raise Kazoo::Error, "Failed to list children of #{path} to delete them. Result code: #{result.fetch(:rc)}" if result.fetch(:rc) != Zookeeper::Constants::ZOK threads = result.fetch(:children).map do |name| Thread.new do Thread.abort_on_exception = true recursive_delete(path: File.join(path, name)) end end threads.each(&:join) result = zk.delete(path: path) raise Kazoo::Error, "Failed to delete node #{path}. Result code: #{result.fetch(:rc)}" if result.fetch(:rc) != Zookeeper::Constants::ZOK end
[ "def", "recursive_delete", "(", "path", ":", "nil", ")", "raise", "ArgumentError", ",", "\"path is a required argument\"", "if", "path", ".", "nil?", "result", "=", "zk", ".", "get_children", "(", "path", ":", "path", ")", "raise", "Kazoo", "::", "Error", ",", "\"Failed to list children of #{path} to delete them. Result code: #{result.fetch(:rc)}\"", "if", "result", ".", "fetch", "(", ":rc", ")", "!=", "Zookeeper", "::", "Constants", "::", "ZOK", "threads", "=", "result", ".", "fetch", "(", ":children", ")", ".", "map", "do", "|", "name", "|", "Thread", ".", "new", "do", "Thread", ".", "abort_on_exception", "=", "true", "recursive_delete", "(", "path", ":", "File", ".", "join", "(", "path", ",", "name", ")", ")", "end", "end", "threads", ".", "each", "(", "&", ":join", ")", "result", "=", "zk", ".", "delete", "(", "path", ":", "path", ")", "raise", "Kazoo", "::", "Error", ",", "\"Failed to delete node #{path}. Result code: #{result.fetch(:rc)}\"", "if", "result", ".", "fetch", "(", ":rc", ")", "!=", "Zookeeper", "::", "Constants", "::", "ZOK", "end" ]
Deletes a node and all of its children from Zookeeper.
[ "Deletes", "a", "node", "and", "all", "of", "its", "children", "from", "Zookeeper", "." ]
54a73612ef4b815fad37ba660eb47353e26165f1
https://github.com/wvanbergen/kazoo/blob/54a73612ef4b815fad37ba660eb47353e26165f1/lib/kazoo/cluster.rb#L154-L170
train
r7kamura/ikku
lib/ikku/reviewer.rb
Ikku.Reviewer.find
def find(text) nodes = parser.parse(text) nodes.length.times.find do |index| if (song = Song.new(nodes[index..-1], rule: @rule)).valid? break song end end end
ruby
def find(text) nodes = parser.parse(text) nodes.length.times.find do |index| if (song = Song.new(nodes[index..-1], rule: @rule)).valid? break song end end end
[ "def", "find", "(", "text", ")", "nodes", "=", "parser", ".", "parse", "(", "text", ")", "nodes", ".", "length", ".", "times", ".", "find", "do", "|", "index", "|", "if", "(", "song", "=", "Song", ".", "new", "(", "nodes", "[", "index", "..", "-", "1", "]", ",", "rule", ":", "@rule", ")", ")", ".", "valid?", "break", "song", "end", "end", "end" ]
Find one valid song from given text. @return [Ikku::Song]
[ "Find", "one", "valid", "song", "from", "given", "text", "." ]
b1f8e51a25b485ec12c13f8650a1d8a1abc83e15
https://github.com/r7kamura/ikku/blob/b1f8e51a25b485ec12c13f8650a1d8a1abc83e15/lib/ikku/reviewer.rb#L12-L19
train
r7kamura/ikku
lib/ikku/reviewer.rb
Ikku.Reviewer.judge
def judge(text) Song.new(parser.parse(text), exactly: true, rule: @rule).valid? end
ruby
def judge(text) Song.new(parser.parse(text), exactly: true, rule: @rule).valid? end
[ "def", "judge", "(", "text", ")", "Song", ".", "new", "(", "parser", ".", "parse", "(", "text", ")", ",", "exactly", ":", "true", ",", "rule", ":", "@rule", ")", ".", "valid?", "end" ]
Judge if given text is valid song or not. @return [true, false]
[ "Judge", "if", "given", "text", "is", "valid", "song", "or", "not", "." ]
b1f8e51a25b485ec12c13f8650a1d8a1abc83e15
https://github.com/r7kamura/ikku/blob/b1f8e51a25b485ec12c13f8650a1d8a1abc83e15/lib/ikku/reviewer.rb#L23-L25
train
r7kamura/ikku
lib/ikku/reviewer.rb
Ikku.Reviewer.search
def search(text) nodes = parser.parse(text) nodes.length.times.map do |index| Song.new(nodes[index..-1], rule: @rule) end.select(&:valid?) end
ruby
def search(text) nodes = parser.parse(text) nodes.length.times.map do |index| Song.new(nodes[index..-1], rule: @rule) end.select(&:valid?) end
[ "def", "search", "(", "text", ")", "nodes", "=", "parser", ".", "parse", "(", "text", ")", "nodes", ".", "length", ".", "times", ".", "map", "do", "|", "index", "|", "Song", ".", "new", "(", "nodes", "[", "index", "..", "-", "1", "]", ",", "rule", ":", "@rule", ")", "end", ".", "select", "(", "&", ":valid?", ")", "end" ]
Search all valid songs from given text. @return [Array<Array>]
[ "Search", "all", "valid", "songs", "from", "given", "text", "." ]
b1f8e51a25b485ec12c13f8650a1d8a1abc83e15
https://github.com/r7kamura/ikku/blob/b1f8e51a25b485ec12c13f8650a1d8a1abc83e15/lib/ikku/reviewer.rb#L29-L34
train
wvanbergen/kazoo
lib/kazoo/broker.rb
Kazoo.Broker.led_partitions
def led_partitions result, mutex = [], Mutex.new threads = cluster.partitions.map do |partition| Thread.new do Thread.abort_on_exception = true select = partition.leader == self mutex.synchronize { result << partition } if select end end threads.each(&:join) result end
ruby
def led_partitions result, mutex = [], Mutex.new threads = cluster.partitions.map do |partition| Thread.new do Thread.abort_on_exception = true select = partition.leader == self mutex.synchronize { result << partition } if select end end threads.each(&:join) result end
[ "def", "led_partitions", "result", ",", "mutex", "=", "[", "]", ",", "Mutex", ".", "new", "threads", "=", "cluster", ".", "partitions", ".", "map", "do", "|", "partition", "|", "Thread", ".", "new", "do", "Thread", ".", "abort_on_exception", "=", "true", "select", "=", "partition", ".", "leader", "==", "self", "mutex", ".", "synchronize", "{", "result", "<<", "partition", "}", "if", "select", "end", "end", "threads", ".", "each", "(", "&", ":join", ")", "result", "end" ]
Returns a list of all partitions that are currently led by this broker.
[ "Returns", "a", "list", "of", "all", "partitions", "that", "are", "currently", "led", "by", "this", "broker", "." ]
54a73612ef4b815fad37ba660eb47353e26165f1
https://github.com/wvanbergen/kazoo/blob/54a73612ef4b815fad37ba660eb47353e26165f1/lib/kazoo/broker.rb#L14-L25
train
wvanbergen/kazoo
lib/kazoo/broker.rb
Kazoo.Broker.replicated_partitions
def replicated_partitions result, mutex = [], Mutex.new threads = cluster.partitions.map do |partition| Thread.new do Thread.abort_on_exception = true select = partition.replicas.include?(self) mutex.synchronize { result << partition } if select end end threads.each(&:join) result end
ruby
def replicated_partitions result, mutex = [], Mutex.new threads = cluster.partitions.map do |partition| Thread.new do Thread.abort_on_exception = true select = partition.replicas.include?(self) mutex.synchronize { result << partition } if select end end threads.each(&:join) result end
[ "def", "replicated_partitions", "result", ",", "mutex", "=", "[", "]", ",", "Mutex", ".", "new", "threads", "=", "cluster", ".", "partitions", ".", "map", "do", "|", "partition", "|", "Thread", ".", "new", "do", "Thread", ".", "abort_on_exception", "=", "true", "select", "=", "partition", ".", "replicas", ".", "include?", "(", "self", ")", "mutex", ".", "synchronize", "{", "result", "<<", "partition", "}", "if", "select", "end", "end", "threads", ".", "each", "(", "&", ":join", ")", "result", "end" ]
Returns a list of all partitions that host a replica on this broker.
[ "Returns", "a", "list", "of", "all", "partitions", "that", "host", "a", "replica", "on", "this", "broker", "." ]
54a73612ef4b815fad37ba660eb47353e26165f1
https://github.com/wvanbergen/kazoo/blob/54a73612ef4b815fad37ba660eb47353e26165f1/lib/kazoo/broker.rb#L28-L39
train
wvanbergen/kazoo
lib/kazoo/broker.rb
Kazoo.Broker.critical?
def critical?(replicas: 1) result, mutex = false, Mutex.new threads = replicated_partitions.map do |partition| Thread.new do Thread.abort_on_exception = true isr = partition.isr.reject { |r| r == self } mutex.synchronize { result = true if isr.length < Integer(replicas) } end end threads.each(&:join) result end
ruby
def critical?(replicas: 1) result, mutex = false, Mutex.new threads = replicated_partitions.map do |partition| Thread.new do Thread.abort_on_exception = true isr = partition.isr.reject { |r| r == self } mutex.synchronize { result = true if isr.length < Integer(replicas) } end end threads.each(&:join) result end
[ "def", "critical?", "(", "replicas", ":", "1", ")", "result", ",", "mutex", "=", "false", ",", "Mutex", ".", "new", "threads", "=", "replicated_partitions", ".", "map", "do", "|", "partition", "|", "Thread", ".", "new", "do", "Thread", ".", "abort_on_exception", "=", "true", "isr", "=", "partition", ".", "isr", ".", "reject", "{", "|", "r", "|", "r", "==", "self", "}", "mutex", ".", "synchronize", "{", "result", "=", "true", "if", "isr", ".", "length", "<", "Integer", "(", "replicas", ")", "}", "end", "end", "threads", ".", "each", "(", "&", ":join", ")", "result", "end" ]
Returns whether this broker is currently considered critical. A broker is considered critical if it is the only in sync replica of any of the partitions it hosts. This means that if this broker were to go down, the partition woild become unavailable for writes, and may also lose data depending on the configuration and settings.
[ "Returns", "whether", "this", "broker", "is", "currently", "considered", "critical", "." ]
54a73612ef4b815fad37ba660eb47353e26165f1
https://github.com/wvanbergen/kazoo/blob/54a73612ef4b815fad37ba660eb47353e26165f1/lib/kazoo/broker.rb#L47-L58
train
archan937/motion-bundler
lib/motion-bundler/mocks/zliby-0.0.5/zlib.rb
Zlib.ZStream.get_bits
def get_bits need val = @bit_bucket while @bit_count < need val |= (@input_buffer[@in_pos+=1] << @bit_count) @bit_count += 8 end @bit_bucket = val >> need @bit_count -= need val & ((1 << need) - 1) end
ruby
def get_bits need val = @bit_bucket while @bit_count < need val |= (@input_buffer[@in_pos+=1] << @bit_count) @bit_count += 8 end @bit_bucket = val >> need @bit_count -= need val & ((1 << need) - 1) end
[ "def", "get_bits", "need", "val", "=", "@bit_bucket", "while", "@bit_count", "<", "need", "val", "|=", "(", "@input_buffer", "[", "@in_pos", "+=", "1", "]", "<<", "@bit_count", ")", "@bit_count", "+=", "8", "end", "@bit_bucket", "=", "val", ">>", "need", "@bit_count", "-=", "need", "val", "&", "(", "(", "1", "<<", "need", ")", "-", "1", ")", "end" ]
returns need bits from the input buffer == Format Notes bits are stored LSB to MSB
[ "returns", "need", "bits", "from", "the", "input", "buffer", "==", "Format", "Notes", "bits", "are", "stored", "LSB", "to", "MSB" ]
9cbfc90d4d4c7d5c61f954760f9568d5cac5b04f
https://github.com/archan937/motion-bundler/blob/9cbfc90d4d4c7d5c61f954760f9568d5cac5b04f/lib/motion-bundler/mocks/zliby-0.0.5/zlib.rb#L171-L181
train
archan937/motion-bundler
lib/motion-bundler/mocks/zliby-0.0.5/zlib.rb
Zlib.Inflate.inflate
def inflate zstring=nil @zstring = zstring unless zstring.nil? #We can't use unpack, IronRuby doesn't have it yet. @zstring.each_byte {|b| @input_buffer << b} unless @rawdeflate then compression_method_and_flags = @input_buffer[@in_pos+=1] flags = @input_buffer[@in_pos+=1] #CMF and FLG, when viewed as a 16-bit unsigned integer stored inMSB order (CMF*256 + FLG), is a multiple of 31 if ((compression_method_and_flags << 0x08) + flags) % 31 != 0 then raise Zlib::DataError.new("incorrect header check") end #CM = 8 denotes the ìdeflateî compression method with a window size up to 32K. (RFC's only specify CM 8) compression_method = compression_method_and_flags & 0x0F if compression_method != Z_DEFLATED then raise Zlib::DataError.new("unknown compression method") end #For CM = 8, CINFO is the base-2 logarithm of the LZ77 window size,minus eight (CINFO=7 indicates a 32K window size) compression_info = compression_method_and_flags >> 0x04 if (compression_info + 8) > @w_bits then raise Zlib::DataError.new("invalid window size") end preset_dictionary_flag = ((flags & 0x20) >> 0x05) == 1 compression_level = (flags & 0xC0) >> 0x06 if preset_dictionary_flag and @dict.nil? then raise Zlib::NeedDict.new "Preset dictionary needed!" end #TODO: Add Preset dictionary support if preset_dictionary_flag then @dict_crc = @input_buffer[@in_pos+=1] << 24 | @input_buffer[@in_pos+=1] << 16 | @input_buffer[@in_pos+=1] << 8 | @input_buffer[@in_pos+=1] end end last_block = false #Begin processing DEFLATE stream until last_block last_block = (get_bits(1) == 1) block_type = get_bits(2) case block_type when 0 then no_compression when 1 then fixed_codes when 2 then dynamic_codes when 3 then raise Zlib::DataError.new("invalid block type") end end finish end
ruby
def inflate zstring=nil @zstring = zstring unless zstring.nil? #We can't use unpack, IronRuby doesn't have it yet. @zstring.each_byte {|b| @input_buffer << b} unless @rawdeflate then compression_method_and_flags = @input_buffer[@in_pos+=1] flags = @input_buffer[@in_pos+=1] #CMF and FLG, when viewed as a 16-bit unsigned integer stored inMSB order (CMF*256 + FLG), is a multiple of 31 if ((compression_method_and_flags << 0x08) + flags) % 31 != 0 then raise Zlib::DataError.new("incorrect header check") end #CM = 8 denotes the ìdeflateî compression method with a window size up to 32K. (RFC's only specify CM 8) compression_method = compression_method_and_flags & 0x0F if compression_method != Z_DEFLATED then raise Zlib::DataError.new("unknown compression method") end #For CM = 8, CINFO is the base-2 logarithm of the LZ77 window size,minus eight (CINFO=7 indicates a 32K window size) compression_info = compression_method_and_flags >> 0x04 if (compression_info + 8) > @w_bits then raise Zlib::DataError.new("invalid window size") end preset_dictionary_flag = ((flags & 0x20) >> 0x05) == 1 compression_level = (flags & 0xC0) >> 0x06 if preset_dictionary_flag and @dict.nil? then raise Zlib::NeedDict.new "Preset dictionary needed!" end #TODO: Add Preset dictionary support if preset_dictionary_flag then @dict_crc = @input_buffer[@in_pos+=1] << 24 | @input_buffer[@in_pos+=1] << 16 | @input_buffer[@in_pos+=1] << 8 | @input_buffer[@in_pos+=1] end end last_block = false #Begin processing DEFLATE stream until last_block last_block = (get_bits(1) == 1) block_type = get_bits(2) case block_type when 0 then no_compression when 1 then fixed_codes when 2 then dynamic_codes when 3 then raise Zlib::DataError.new("invalid block type") end end finish end
[ "def", "inflate", "zstring", "=", "nil", "@zstring", "=", "zstring", "unless", "zstring", ".", "nil?", "@zstring", ".", "each_byte", "{", "|", "b", "|", "@input_buffer", "<<", "b", "}", "unless", "@rawdeflate", "then", "compression_method_and_flags", "=", "@input_buffer", "[", "@in_pos", "+=", "1", "]", "flags", "=", "@input_buffer", "[", "@in_pos", "+=", "1", "]", "if", "(", "(", "compression_method_and_flags", "<<", "0x08", ")", "+", "flags", ")", "%", "31", "!=", "0", "then", "raise", "Zlib", "::", "DataError", ".", "new", "(", "\"incorrect header check\"", ")", "end", "compression_method", "=", "compression_method_and_flags", "&", "0x0F", "if", "compression_method", "!=", "Z_DEFLATED", "then", "raise", "Zlib", "::", "DataError", ".", "new", "(", "\"unknown compression method\"", ")", "end", "compression_info", "=", "compression_method_and_flags", ">>", "0x04", "if", "(", "compression_info", "+", "8", ")", ">", "@w_bits", "then", "raise", "Zlib", "::", "DataError", ".", "new", "(", "\"invalid window size\"", ")", "end", "preset_dictionary_flag", "=", "(", "(", "flags", "&", "0x20", ")", ">>", "0x05", ")", "==", "1", "compression_level", "=", "(", "flags", "&", "0xC0", ")", ">>", "0x06", "if", "preset_dictionary_flag", "and", "@dict", ".", "nil?", "then", "raise", "Zlib", "::", "NeedDict", ".", "new", "\"Preset dictionary needed!\"", "end", "if", "preset_dictionary_flag", "then", "@dict_crc", "=", "@input_buffer", "[", "@in_pos", "+=", "1", "]", "<<", "24", "|", "@input_buffer", "[", "@in_pos", "+=", "1", "]", "<<", "16", "|", "@input_buffer", "[", "@in_pos", "+=", "1", "]", "<<", "8", "|", "@input_buffer", "[", "@in_pos", "+=", "1", "]", "end", "end", "last_block", "=", "false", "until", "last_block", "last_block", "=", "(", "get_bits", "(", "1", ")", "==", "1", ")", "block_type", "=", "get_bits", "(", "2", ")", "case", "block_type", "when", "0", "then", "no_compression", "when", "1", "then", "fixed_codes", "when", "2", "then", "dynamic_codes", "when", "3", "then", "raise", "Zlib", "::", "DataError", ".", "new", "(", "\"invalid block type\"", ")", "end", "end", "finish", "end" ]
==Example f = File.open "example.z" i = Inflate.new i.inflate f.read
[ "==", "Example", "f", "=", "File", ".", "open", "example", ".", "z", "i", "=", "Inflate", ".", "new", "i", ".", "inflate", "f", ".", "read" ]
9cbfc90d4d4c7d5c61f954760f9568d5cac5b04f
https://github.com/archan937/motion-bundler/blob/9cbfc90d4d4c7d5c61f954760f9568d5cac5b04f/lib/motion-bundler/mocks/zliby-0.0.5/zlib.rb#L215-L262
train
octopress/hooks
lib/octopress-hooks.rb
Jekyll.Convertible.do_layout
def do_layout(payload, layouts) pre_render if respond_to?(:pre_render) && hooks if respond_to?(:merge_payload) && hooks old_do_layout(merge_payload(payload.dup), layouts) else old_do_layout(payload, layouts) end post_render if respond_to?(:post_render) && hooks end
ruby
def do_layout(payload, layouts) pre_render if respond_to?(:pre_render) && hooks if respond_to?(:merge_payload) && hooks old_do_layout(merge_payload(payload.dup), layouts) else old_do_layout(payload, layouts) end post_render if respond_to?(:post_render) && hooks end
[ "def", "do_layout", "(", "payload", ",", "layouts", ")", "pre_render", "if", "respond_to?", "(", ":pre_render", ")", "&&", "hooks", "if", "respond_to?", "(", ":merge_payload", ")", "&&", "hooks", "old_do_layout", "(", "merge_payload", "(", "payload", ".", "dup", ")", ",", "layouts", ")", "else", "old_do_layout", "(", "payload", ",", "layouts", ")", "end", "post_render", "if", "respond_to?", "(", ":post_render", ")", "&&", "hooks", "end" ]
Calls the pre_render method if it exists and then adds any necessary layouts to this convertible document. payload - The site payload Hash. layouts - A Hash of {"name" => "layout"}. Returns nothing.
[ "Calls", "the", "pre_render", "method", "if", "it", "exists", "and", "then", "adds", "any", "necessary", "layouts", "to", "this", "convertible", "document", "." ]
ac460266254ed23e7d656767ec346eea63b29788
https://github.com/octopress/hooks/blob/ac460266254ed23e7d656767ec346eea63b29788/lib/octopress-hooks.rb#L346-L356
train
octopress/hooks
lib/octopress-hooks.rb
Jekyll.Site.site_payload
def site_payload @cached_payload = begin payload = old_site_payload site_hooks.each do |hook| p = hook.merge_payload(payload, self) next unless p && p.is_a?(Hash) payload = Jekyll::Utils.deep_merge_hashes(payload, p) end payload end end
ruby
def site_payload @cached_payload = begin payload = old_site_payload site_hooks.each do |hook| p = hook.merge_payload(payload, self) next unless p && p.is_a?(Hash) payload = Jekyll::Utils.deep_merge_hashes(payload, p) end payload end end
[ "def", "site_payload", "@cached_payload", "=", "begin", "payload", "=", "old_site_payload", "site_hooks", ".", "each", "do", "|", "hook", "|", "p", "=", "hook", ".", "merge_payload", "(", "payload", ",", "self", ")", "next", "unless", "p", "&&", "p", ".", "is_a?", "(", "Hash", ")", "payload", "=", "Jekyll", "::", "Utils", ".", "deep_merge_hashes", "(", "payload", ",", "p", ")", "end", "payload", "end", "end" ]
Allows site hooks to merge data into the site payload Returns the patched site payload
[ "Allows", "site", "hooks", "to", "merge", "data", "into", "the", "site", "payload" ]
ac460266254ed23e7d656767ec346eea63b29788
https://github.com/octopress/hooks/blob/ac460266254ed23e7d656767ec346eea63b29788/lib/octopress-hooks.rb#L203-L214
train
oliamb/knnball
lib/knnball/ball.rb
KnnBall.Ball.distance
def distance(coordinates) coordinates = coordinates.center if coordinates.respond_to?(:center) Math.sqrt([center, coordinates].transpose.map {|a,b| (b - a)**2}.reduce {|d1,d2| d1 + d2}) end
ruby
def distance(coordinates) coordinates = coordinates.center if coordinates.respond_to?(:center) Math.sqrt([center, coordinates].transpose.map {|a,b| (b - a)**2}.reduce {|d1,d2| d1 + d2}) end
[ "def", "distance", "(", "coordinates", ")", "coordinates", "=", "coordinates", ".", "center", "if", "coordinates", ".", "respond_to?", "(", ":center", ")", "Math", ".", "sqrt", "(", "[", "center", ",", "coordinates", "]", ".", "transpose", ".", "map", "{", "|", "a", ",", "b", "|", "(", "b", "-", "a", ")", "**", "2", "}", ".", "reduce", "{", "|", "d1", ",", "d2", "|", "d1", "+", "d2", "}", ")", "end" ]
Compute euclidien distance. @param coordinates an array of coord or a Ball instance
[ "Compute", "euclidien", "distance", "." ]
eb67c4452481d727ded06984ba7d82a92b5a8e03
https://github.com/oliamb/knnball/blob/eb67c4452481d727ded06984ba7d82a92b5a8e03/lib/knnball/ball.rb#L78-L81
train
rkh/tool
lib/tool/decoration.rb
Tool.Decoration.decorate
def decorate(block = nil, name: "generated", &callback) @decorations << callback if block alias_name = "__" << name.to_s.downcase.gsub(/[^a-z]+/, ?_) << ?1 alias_name = alias_name.succ while private_method_defined? alias_name or method_defined? alias_name without_decorations { define_method(name, &block) } alias_method(alias_name, name) remove_method(name) private(alias_name) end end
ruby
def decorate(block = nil, name: "generated", &callback) @decorations << callback if block alias_name = "__" << name.to_s.downcase.gsub(/[^a-z]+/, ?_) << ?1 alias_name = alias_name.succ while private_method_defined? alias_name or method_defined? alias_name without_decorations { define_method(name, &block) } alias_method(alias_name, name) remove_method(name) private(alias_name) end end
[ "def", "decorate", "(", "block", "=", "nil", ",", "name", ":", "\"generated\"", ",", "&", "callback", ")", "@decorations", "<<", "callback", "if", "block", "alias_name", "=", "\"__\"", "<<", "name", ".", "to_s", ".", "downcase", ".", "gsub", "(", "/", "/", ",", "?_", ")", "<<", "?1", "alias_name", "=", "alias_name", ".", "succ", "while", "private_method_defined?", "alias_name", "or", "method_defined?", "alias_name", "without_decorations", "{", "define_method", "(", "name", ",", "&", "block", ")", "}", "alias_method", "(", "alias_name", ",", "name", ")", "remove_method", "(", "name", ")", "private", "(", "alias_name", ")", "end", "end" ]
Set up a decoration. @param [Proc, UnboundMethod, nil] block used for defining a method right away @param [String, Symbol] name given to the generated method if block is given @yield callback called with method name once method is defined @yieldparam [Symbol] method name of the method that is to be decorated
[ "Set", "up", "a", "decoration", "." ]
9a84fc6a60ecdf51cf17e90ae1331b4550d5d677
https://github.com/rkh/tool/blob/9a84fc6a60ecdf51cf17e90ae1331b4550d5d677/lib/tool/decoration.rb#L67-L78
train
nikhgupta/scrapix
lib/scrapix/vbulletin.rb
Scrapix.VBulletin.find
def find reset; return @images unless @url @page_no = @options["start"] until @images.count > @options["total"] || thread_has_ended? page = @agent.get "#{@url}&page=#{@page_no}" puts "[VERBOSE] Searching: #{@url}&page=#{@page_no}" if @options["verbose"] && options["cli"] sources = page.image_urls.map{|x| x.to_s} sources = filter_images sources # hook for sub-classes @page_no += 1 continue if sources.empty? sources.each do |source| hash = Digest::MD5.hexdigest(source) unless @images.has_key?(hash) @images[hash] = {url: source} puts source if options["cli"] end end end @images = @images.map{|x, y| y} end
ruby
def find reset; return @images unless @url @page_no = @options["start"] until @images.count > @options["total"] || thread_has_ended? page = @agent.get "#{@url}&page=#{@page_no}" puts "[VERBOSE] Searching: #{@url}&page=#{@page_no}" if @options["verbose"] && options["cli"] sources = page.image_urls.map{|x| x.to_s} sources = filter_images sources # hook for sub-classes @page_no += 1 continue if sources.empty? sources.each do |source| hash = Digest::MD5.hexdigest(source) unless @images.has_key?(hash) @images[hash] = {url: source} puts source if options["cli"] end end end @images = @images.map{|x, y| y} end
[ "def", "find", "reset", ";", "return", "@images", "unless", "@url", "@page_no", "=", "@options", "[", "\"start\"", "]", "until", "@images", ".", "count", ">", "@options", "[", "\"total\"", "]", "||", "thread_has_ended?", "page", "=", "@agent", ".", "get", "\"#{@url}&page=#{@page_no}\"", "puts", "\"[VERBOSE] Searching: #{@url}&page=#{@page_no}\"", "if", "@options", "[", "\"verbose\"", "]", "&&", "options", "[", "\"cli\"", "]", "sources", "=", "page", ".", "image_urls", ".", "map", "{", "|", "x", "|", "x", ".", "to_s", "}", "sources", "=", "filter_images", "sources", "@page_no", "+=", "1", "continue", "if", "sources", ".", "empty?", "sources", ".", "each", "do", "|", "source", "|", "hash", "=", "Digest", "::", "MD5", ".", "hexdigest", "(", "source", ")", "unless", "@images", ".", "has_key?", "(", "hash", ")", "@images", "[", "hash", "]", "=", "{", "url", ":", "source", "}", "puts", "source", "if", "options", "[", "\"cli\"", "]", "end", "end", "end", "@images", "=", "@images", ".", "map", "{", "|", "x", ",", "y", "|", "y", "}", "end" ]
find images for this thread, specified by starting page_no
[ "find", "images", "for", "this", "thread", "specified", "by", "starting", "page_no" ]
0a28a57a4ca423fb275e0d4e63fc1b9a824d9819
https://github.com/nikhgupta/scrapix/blob/0a28a57a4ca423fb275e0d4e63fc1b9a824d9819/lib/scrapix/vbulletin.rb#L16-L35
train
NFesquet/danger-kotlin_detekt
lib/kotlin_detekt/plugin.rb
Danger.DangerKotlinDetekt.detekt
def detekt(inline_mode: false) unless skip_gradle_task || gradlew_exists? fail("Could not find `gradlew` inside current directory") return end unless SEVERITY_LEVELS.include?(severity) fail("'#{severity}' is not a valid value for `severity` parameter.") return end system "./gradlew #{gradle_task || 'detektCheck'}" unless skip_gradle_task unless File.exist?(report_file) fail("Detekt report not found at `#{report_file}`. "\ "Have you forgot to add `xmlReport true` to your `build.gradle` file?") end issues = read_issues_from_report filtered_issues = filter_issues_by_severity(issues) if inline_mode # Report with inline comment send_inline_comment(filtered_issues) else message = message_for_issues(filtered_issues) markdown("### Detekt found issues\n\n" + message) unless message.to_s.empty? end end
ruby
def detekt(inline_mode: false) unless skip_gradle_task || gradlew_exists? fail("Could not find `gradlew` inside current directory") return end unless SEVERITY_LEVELS.include?(severity) fail("'#{severity}' is not a valid value for `severity` parameter.") return end system "./gradlew #{gradle_task || 'detektCheck'}" unless skip_gradle_task unless File.exist?(report_file) fail("Detekt report not found at `#{report_file}`. "\ "Have you forgot to add `xmlReport true` to your `build.gradle` file?") end issues = read_issues_from_report filtered_issues = filter_issues_by_severity(issues) if inline_mode # Report with inline comment send_inline_comment(filtered_issues) else message = message_for_issues(filtered_issues) markdown("### Detekt found issues\n\n" + message) unless message.to_s.empty? end end
[ "def", "detekt", "(", "inline_mode", ":", "false", ")", "unless", "skip_gradle_task", "||", "gradlew_exists?", "fail", "(", "\"Could not find `gradlew` inside current directory\"", ")", "return", "end", "unless", "SEVERITY_LEVELS", ".", "include?", "(", "severity", ")", "fail", "(", "\"'#{severity}' is not a valid value for `severity` parameter.\"", ")", "return", "end", "system", "\"./gradlew #{gradle_task || 'detektCheck'}\"", "unless", "skip_gradle_task", "unless", "File", ".", "exist?", "(", "report_file", ")", "fail", "(", "\"Detekt report not found at `#{report_file}`. \"", "\"Have you forgot to add `xmlReport true` to your `build.gradle` file?\"", ")", "end", "issues", "=", "read_issues_from_report", "filtered_issues", "=", "filter_issues_by_severity", "(", "issues", ")", "if", "inline_mode", "send_inline_comment", "(", "filtered_issues", ")", "else", "message", "=", "message_for_issues", "(", "filtered_issues", ")", "markdown", "(", "\"### Detekt found issues\\n\\n\"", "+", "message", ")", "unless", "message", ".", "to_s", ".", "empty?", "end", "end" ]
Calls Detekt task of your gradle project. It fails if `gradlew` cannot be found inside current directory. It fails if `severity` level is not a valid option. It fails if `xmlReport` configuration is not set to `true` in your `build.gradle` file. @return [void]
[ "Calls", "Detekt", "task", "of", "your", "gradle", "project", ".", "It", "fails", "if", "gradlew", "cannot", "be", "found", "inside", "current", "directory", ".", "It", "fails", "if", "severity", "level", "is", "not", "a", "valid", "option", ".", "It", "fails", "if", "xmlReport", "configuration", "is", "not", "set", "to", "true", "in", "your", "build", ".", "gradle", "file", "." ]
b45824e4bc8e02feb4f3fc78cb7e2741cb7fcdb5
https://github.com/NFesquet/danger-kotlin_detekt/blob/b45824e4bc8e02feb4f3fc78cb7e2741cb7fcdb5/lib/kotlin_detekt/plugin.rb#L64-L92
train
chef-boneyard/winrm-s
lib/winrm/winrm_service_patch.rb
WinRM.WinRMWebService.get_builder_obj
def get_builder_obj(shell_id, command_id, &block) body = { "#{NS_WIN_SHELL}:DesiredStream" => 'stdout stderr', :attributes! => {"#{NS_WIN_SHELL}:DesiredStream" => {'CommandId' => command_id}}} builder = Builder::XmlMarkup.new builder.instruct!(:xml, :encoding => 'UTF-8') builder.tag! :env, :Envelope, namespaces do |env| env.tag!(:env, :Header) { |h| h << Gyoku.xml(merge_headers(header,resource_uri_cmd,action_receive,selector_shell_id(shell_id))) } env.tag!(:env, :Body) do |env_body| env_body.tag!("#{NS_WIN_SHELL}:Receive") { |cl| cl << Gyoku.xml(body) } end end builder end
ruby
def get_builder_obj(shell_id, command_id, &block) body = { "#{NS_WIN_SHELL}:DesiredStream" => 'stdout stderr', :attributes! => {"#{NS_WIN_SHELL}:DesiredStream" => {'CommandId' => command_id}}} builder = Builder::XmlMarkup.new builder.instruct!(:xml, :encoding => 'UTF-8') builder.tag! :env, :Envelope, namespaces do |env| env.tag!(:env, :Header) { |h| h << Gyoku.xml(merge_headers(header,resource_uri_cmd,action_receive,selector_shell_id(shell_id))) } env.tag!(:env, :Body) do |env_body| env_body.tag!("#{NS_WIN_SHELL}:Receive") { |cl| cl << Gyoku.xml(body) } end end builder end
[ "def", "get_builder_obj", "(", "shell_id", ",", "command_id", ",", "&", "block", ")", "body", "=", "{", "\"#{NS_WIN_SHELL}:DesiredStream\"", "=>", "'stdout stderr'", ",", ":attributes!", "=>", "{", "\"#{NS_WIN_SHELL}:DesiredStream\"", "=>", "{", "'CommandId'", "=>", "command_id", "}", "}", "}", "builder", "=", "Builder", "::", "XmlMarkup", ".", "new", "builder", ".", "instruct!", "(", ":xml", ",", ":encoding", "=>", "'UTF-8'", ")", "builder", ".", "tag!", ":env", ",", ":Envelope", ",", "namespaces", "do", "|", "env", "|", "env", ".", "tag!", "(", ":env", ",", ":Header", ")", "{", "|", "h", "|", "h", "<<", "Gyoku", ".", "xml", "(", "merge_headers", "(", "header", ",", "resource_uri_cmd", ",", "action_receive", ",", "selector_shell_id", "(", "shell_id", ")", ")", ")", "}", "env", ".", "tag!", "(", ":env", ",", ":Body", ")", "do", "|", "env_body", "|", "env_body", ".", "tag!", "(", "\"#{NS_WIN_SHELL}:Receive\"", ")", "{", "|", "cl", "|", "cl", "<<", "Gyoku", ".", "xml", "(", "body", ")", "}", "end", "end", "builder", "end" ]
Override winrm to support sspinegotiate option. @param [String,URI] endpoint the WinRM webservice endpoint @param [Symbol] transport either :kerberos(default)/:ssl/:plaintext @param [Hash] opts Misc opts for the various transports. @see WinRM::HTTP::HttpTransport @see WinRM::HTTP::HttpGSSAPI @see WinRM::HTTP::HttpSSL Get the builder obj for output request @param [String] shell_id The shell id on the remote machine. See #open_shell @param [String] command_id The command id on the remote machine. See #run_command @return [Builder::XmlMarkup] Returns a Builder::XmlMarkup for request message
[ "Override", "winrm", "to", "support", "sspinegotiate", "option", "." ]
6c0e9027a79acfb9252caa701b1b383073bee865
https://github.com/chef-boneyard/winrm-s/blob/6c0e9027a79acfb9252caa701b1b383073bee865/lib/winrm/winrm_service_patch.rb#L41-L53
train
chef-boneyard/winrm-s
lib/winrm/winrm_service_patch.rb
WinRM.WinRMWebService.get_command_output
def get_command_output(shell_id, command_id, &block) done_elems = [] output = Output.new while done_elems.empty? resp_doc = nil builder = get_builder_obj(shell_id, command_id, &block) request_msg = builder.target! resp_doc = send_get_output_message(request_msg) REXML::XPath.match(resp_doc, "//#{NS_WIN_SHELL}:Stream").each do |n| next if n.text.nil? || n.text.empty? stream = { n.attributes['Name'].to_sym => Base64.decode64(n.text).force_encoding('utf-8').sub("\xEF\xBB\xBF", "") } output[:data] << stream yield stream[:stdout], stream[:stderr] if block_given? end # We may need to get additional output if the stream has not finished. # The CommandState will change from Running to Done like so: # @example # from... # <rsp:CommandState CommandId="..." State="http://schemas.microsoft.com/wbem/wsman/1/windows/shell/CommandState/Running"/> # to... # <rsp:CommandState CommandId="..." State="http://schemas.microsoft.com/wbem/wsman/1/windows/shell/CommandState/Done"> # <rsp:ExitCode>0</rsp:ExitCode> # </rsp:CommandState> done_elems = REXML::XPath.match(resp_doc, "//*[@State='http://schemas.microsoft.com/wbem/wsman/1/windows/shell/CommandState/Done']") end output[:exitcode] = REXML::XPath.first(resp_doc, "//#{NS_WIN_SHELL}:ExitCode").text.to_i output end
ruby
def get_command_output(shell_id, command_id, &block) done_elems = [] output = Output.new while done_elems.empty? resp_doc = nil builder = get_builder_obj(shell_id, command_id, &block) request_msg = builder.target! resp_doc = send_get_output_message(request_msg) REXML::XPath.match(resp_doc, "//#{NS_WIN_SHELL}:Stream").each do |n| next if n.text.nil? || n.text.empty? stream = { n.attributes['Name'].to_sym => Base64.decode64(n.text).force_encoding('utf-8').sub("\xEF\xBB\xBF", "") } output[:data] << stream yield stream[:stdout], stream[:stderr] if block_given? end # We may need to get additional output if the stream has not finished. # The CommandState will change from Running to Done like so: # @example # from... # <rsp:CommandState CommandId="..." State="http://schemas.microsoft.com/wbem/wsman/1/windows/shell/CommandState/Running"/> # to... # <rsp:CommandState CommandId="..." State="http://schemas.microsoft.com/wbem/wsman/1/windows/shell/CommandState/Done"> # <rsp:ExitCode>0</rsp:ExitCode> # </rsp:CommandState> done_elems = REXML::XPath.match(resp_doc, "//*[@State='http://schemas.microsoft.com/wbem/wsman/1/windows/shell/CommandState/Done']") end output[:exitcode] = REXML::XPath.first(resp_doc, "//#{NS_WIN_SHELL}:ExitCode").text.to_i output end
[ "def", "get_command_output", "(", "shell_id", ",", "command_id", ",", "&", "block", ")", "done_elems", "=", "[", "]", "output", "=", "Output", ".", "new", "while", "done_elems", ".", "empty?", "resp_doc", "=", "nil", "builder", "=", "get_builder_obj", "(", "shell_id", ",", "command_id", ",", "&", "block", ")", "request_msg", "=", "builder", ".", "target!", "resp_doc", "=", "send_get_output_message", "(", "request_msg", ")", "REXML", "::", "XPath", ".", "match", "(", "resp_doc", ",", "\"//#{NS_WIN_SHELL}:Stream\"", ")", ".", "each", "do", "|", "n", "|", "next", "if", "n", ".", "text", ".", "nil?", "||", "n", ".", "text", ".", "empty?", "stream", "=", "{", "n", ".", "attributes", "[", "'Name'", "]", ".", "to_sym", "=>", "Base64", ".", "decode64", "(", "n", ".", "text", ")", ".", "force_encoding", "(", "'utf-8'", ")", ".", "sub", "(", "\"\\xEF\\xBB\\xBF\"", ",", "\"\"", ")", "}", "output", "[", ":data", "]", "<<", "stream", "yield", "stream", "[", ":stdout", "]", ",", "stream", "[", ":stderr", "]", "if", "block_given?", "end", "done_elems", "=", "REXML", "::", "XPath", ".", "match", "(", "resp_doc", ",", "\"//*[@State='http://schemas.microsoft.com/wbem/wsman/1/windows/shell/CommandState/Done']\"", ")", "end", "output", "[", ":exitcode", "]", "=", "REXML", "::", "XPath", ".", "first", "(", "resp_doc", ",", "\"//#{NS_WIN_SHELL}:ExitCode\"", ")", ".", "text", ".", "to_i", "output", "end" ]
Get the Output of the given shell and command @param [String] shell_id The shell id on the remote machine. See #open_shell @param [String] command_id The command id on the remote machine. See #run_command @return [Hash] Returns a Hash with a key :exitcode and :data. Data is an Array of Hashes where the cooresponding key is either :stdout or :stderr. The reason it is in an Array so so we can get the output in the order it ocurrs on the console.
[ "Get", "the", "Output", "of", "the", "given", "shell", "and", "command" ]
6c0e9027a79acfb9252caa701b1b383073bee865
https://github.com/chef-boneyard/winrm-s/blob/6c0e9027a79acfb9252caa701b1b383073bee865/lib/winrm/winrm_service_patch.rb#L61-L91
train
argosity/hippo
lib/hippo/concerns/set_attribute_data.rb
Hippo::Concerns.ApiAttributeAccess.setting_attribute_is_allowed?
def setting_attribute_is_allowed?(name, user) return false unless user.can_write?(self, name) (self.whitelisted_attributes && self.whitelisted_attributes.has_key?( name.to_sym)) || ( self.attribute_names.include?( name.to_s ) && ( self.blacklisted_attributes.nil? || ! self.blacklisted_attributes.has_key?( name.to_sym ) ) ) end
ruby
def setting_attribute_is_allowed?(name, user) return false unless user.can_write?(self, name) (self.whitelisted_attributes && self.whitelisted_attributes.has_key?( name.to_sym)) || ( self.attribute_names.include?( name.to_s ) && ( self.blacklisted_attributes.nil? || ! self.blacklisted_attributes.has_key?( name.to_sym ) ) ) end
[ "def", "setting_attribute_is_allowed?", "(", "name", ",", "user", ")", "return", "false", "unless", "user", ".", "can_write?", "(", "self", ",", "name", ")", "(", "self", ".", "whitelisted_attributes", "&&", "self", ".", "whitelisted_attributes", ".", "has_key?", "(", "name", ".", "to_sym", ")", ")", "||", "(", "self", ".", "attribute_names", ".", "include?", "(", "name", ".", "to_s", ")", "&&", "(", "self", ".", "blacklisted_attributes", ".", "nil?", "||", "!", "self", ".", "blacklisted_attributes", ".", "has_key?", "(", "name", ".", "to_sym", ")", ")", ")", "end" ]
An attribute is allowed if it's white listed or it's a valid attribute and not black listed @param name [Symbol] @param user [User] who is performing request
[ "An", "attribute", "is", "allowed", "if", "it", "s", "white", "listed", "or", "it", "s", "a", "valid", "attribute", "and", "not", "black", "listed" ]
83be4c164897be3854325ff7fe0854604740df5e
https://github.com/argosity/hippo/blob/83be4c164897be3854325ff7fe0854604740df5e/lib/hippo/concerns/set_attribute_data.rb#L64-L72
train
openc/turbot-client
lib/turbot/helpers/api_helper.rb
Turbot.Helpers.turbot_api_parameters
def turbot_api_parameters uri = URI.parse(host) { :host => uri.host, :port => uri.port, :scheme => uri.scheme, } end
ruby
def turbot_api_parameters uri = URI.parse(host) { :host => uri.host, :port => uri.port, :scheme => uri.scheme, } end
[ "def", "turbot_api_parameters", "uri", "=", "URI", ".", "parse", "(", "host", ")", "{", ":host", "=>", "uri", ".", "host", ",", ":port", "=>", "uri", ".", "port", ",", ":scheme", "=>", "uri", ".", "scheme", ",", "}", "end" ]
Returns the parameters for the Turbot API, based on the base URL of the Turbot server. @return [Hash] the parameters for the Turbot API
[ "Returns", "the", "parameters", "for", "the", "Turbot", "API", "based", "on", "the", "base", "URL", "of", "the", "Turbot", "server", "." ]
01225a5c7e155b7b34f1ae8de107c0b97201b42d
https://github.com/openc/turbot-client/blob/01225a5c7e155b7b34f1ae8de107c0b97201b42d/lib/turbot/helpers/api_helper.rb#L20-L28
train
flinc/pling
lib/pling/gateway.rb
Pling.Gateway.handles?
def handles?(device) device = Pling._convert(device, :device) self.class.handled_types.include?(device.type) end
ruby
def handles?(device) device = Pling._convert(device, :device) self.class.handled_types.include?(device.type) end
[ "def", "handles?", "(", "device", ")", "device", "=", "Pling", ".", "_convert", "(", "device", ",", ":device", ")", "self", ".", "class", ".", "handled_types", ".", "include?", "(", "device", ".", "type", ")", "end" ]
Checks if this gateway is able to handle the given device @param device [#to_pling_device] @return [Boolean]
[ "Checks", "if", "this", "gateway", "is", "able", "to", "handle", "the", "given", "device" ]
fdbf998a393502de4fd193b5ffb454bd4b100ac6
https://github.com/flinc/pling/blob/fdbf998a393502de4fd193b5ffb454bd4b100ac6/lib/pling/gateway.rb#L85-L88
train
kiwanami/ruby-elparser
lib/elparser.rb
Elparser.SExpList.to_h
def to_h ret = Hash.new @list.each do |i| ret[i.car.to_ruby] = i.cdr.to_ruby end ret end
ruby
def to_h ret = Hash.new @list.each do |i| ret[i.car.to_ruby] = i.cdr.to_ruby end ret end
[ "def", "to_h", "ret", "=", "Hash", ".", "new", "@list", ".", "each", "do", "|", "i", "|", "ret", "[", "i", ".", "car", ".", "to_ruby", "]", "=", "i", ".", "cdr", ".", "to_ruby", "end", "ret", "end" ]
alist -> hash
[ "alist", "-", ">", "hash" ]
7b7edd13d7a3bd1a8a092983950aa5a9cc1cad5d
https://github.com/kiwanami/ruby-elparser/blob/7b7edd13d7a3bd1a8a092983950aa5a9cc1cad5d/lib/elparser.rb#L172-L178
train
kiwanami/ruby-elparser
lib/elparser.rb
Elparser.Parser.parse
def parse(str) if str.nil? || str == "" raise ParserError.new("Empty input",0,"") end s = StringScanner.new str @tokens = [] until s.eos? s.skip(/\s+/) ? nil : s.scan(/\A[-+]?[0-9]*\.[0-9]+(e[-+]?[0-9]+)?/i) ? (@tokens << [:FLOAT, s.matched]) : s.scan(/\A[-+]?(0|[1-9]\d*)/) ? (@tokens << [:INTEGER, s.matched]) : s.scan(/\A\.(?=\s)/) ? (@tokens << ['.', '.']) : s.scan(/\A[a-z\-.\/_:*<>+=$#][a-z\-.\/_:$*<>+=0-9]*/i) ? (@tokens << [:SYMBOL, s.matched]) : s.scan(/\A"(([^\\"]|\\.)*)"/) ? (@tokens << [:STRING, _unescape_string(s.matched.slice(1...-1))]) : s.scan(/\A./) ? (a = s.matched; @tokens << [a, a]) : (raise ParserError.new("Scanner error",s.pos,s.peek(5))) end @tokens.push [false, 'END'] return do_parse.map do |i| normalize(i) end end
ruby
def parse(str) if str.nil? || str == "" raise ParserError.new("Empty input",0,"") end s = StringScanner.new str @tokens = [] until s.eos? s.skip(/\s+/) ? nil : s.scan(/\A[-+]?[0-9]*\.[0-9]+(e[-+]?[0-9]+)?/i) ? (@tokens << [:FLOAT, s.matched]) : s.scan(/\A[-+]?(0|[1-9]\d*)/) ? (@tokens << [:INTEGER, s.matched]) : s.scan(/\A\.(?=\s)/) ? (@tokens << ['.', '.']) : s.scan(/\A[a-z\-.\/_:*<>+=$#][a-z\-.\/_:$*<>+=0-9]*/i) ? (@tokens << [:SYMBOL, s.matched]) : s.scan(/\A"(([^\\"]|\\.)*)"/) ? (@tokens << [:STRING, _unescape_string(s.matched.slice(1...-1))]) : s.scan(/\A./) ? (a = s.matched; @tokens << [a, a]) : (raise ParserError.new("Scanner error",s.pos,s.peek(5))) end @tokens.push [false, 'END'] return do_parse.map do |i| normalize(i) end end
[ "def", "parse", "(", "str", ")", "if", "str", ".", "nil?", "||", "str", "==", "\"\"", "raise", "ParserError", ".", "new", "(", "\"Empty input\"", ",", "0", ",", "\"\"", ")", "end", "s", "=", "StringScanner", ".", "new", "str", "@tokens", "=", "[", "]", "until", "s", ".", "eos?", "s", ".", "skip", "(", "/", "\\s", "/", ")", "?", "nil", ":", "s", ".", "scan", "(", "/", "\\A", "\\.", "/i", ")", "?", "(", "@tokens", "<<", "[", ":FLOAT", ",", "s", ".", "matched", "]", ")", ":", "s", ".", "scan", "(", "/", "\\A", "\\d", "/", ")", "?", "(", "@tokens", "<<", "[", ":INTEGER", ",", "s", ".", "matched", "]", ")", ":", "s", ".", "scan", "(", "/", "\\A", "\\.", "\\s", "/", ")", "?", "(", "@tokens", "<<", "[", "'.'", ",", "'.'", "]", ")", ":", "s", ".", "scan", "(", "/", "\\A", "\\-", "\\/", "\\-", "\\/", "/i", ")", "?", "(", "@tokens", "<<", "[", ":SYMBOL", ",", "s", ".", "matched", "]", ")", ":", "s", ".", "scan", "(", "/", "\\A", "\\\\", "\\\\", "/", ")", "?", "(", "@tokens", "<<", "[", ":STRING", ",", "_unescape_string", "(", "s", ".", "matched", ".", "slice", "(", "1", "...", "-", "1", ")", ")", "]", ")", ":", "s", ".", "scan", "(", "/", "\\A", "/", ")", "?", "(", "a", "=", "s", ".", "matched", ";", "@tokens", "<<", "[", "a", ",", "a", "]", ")", ":", "(", "raise", "ParserError", ".", "new", "(", "\"Scanner error\"", ",", "s", ".", "pos", ",", "s", ".", "peek", "(", "5", ")", ")", ")", "end", "@tokens", ".", "push", "[", "false", ",", "'END'", "]", "return", "do_parse", ".", "map", "do", "|", "i", "|", "normalize", "(", "i", ")", "end", "end" ]
parse s-expression string and return sexp objects.
[ "parse", "s", "-", "expression", "string", "and", "return", "sexp", "objects", "." ]
7b7edd13d7a3bd1a8a092983950aa5a9cc1cad5d
https://github.com/kiwanami/ruby-elparser/blob/7b7edd13d7a3bd1a8a092983950aa5a9cc1cad5d/lib/elparser.rb#L245-L268
train
kiwanami/ruby-elparser
lib/elparser.rb
Elparser.Parser.normalize
def normalize(ast) if ast.class == SExpSymbol case ast.name when "nil" return SExpNil.new else return ast end elsif ast.cons? then ast.visit do |i| normalize(i) end end return ast end
ruby
def normalize(ast) if ast.class == SExpSymbol case ast.name when "nil" return SExpNil.new else return ast end elsif ast.cons? then ast.visit do |i| normalize(i) end end return ast end
[ "def", "normalize", "(", "ast", ")", "if", "ast", ".", "class", "==", "SExpSymbol", "case", "ast", ".", "name", "when", "\"nil\"", "return", "SExpNil", ".", "new", "else", "return", "ast", "end", "elsif", "ast", ".", "cons?", "then", "ast", ".", "visit", "do", "|", "i", "|", "normalize", "(", "i", ")", "end", "end", "return", "ast", "end" ]
replace special symbols
[ "replace", "special", "symbols" ]
7b7edd13d7a3bd1a8a092983950aa5a9cc1cad5d
https://github.com/kiwanami/ruby-elparser/blob/7b7edd13d7a3bd1a8a092983950aa5a9cc1cad5d/lib/elparser.rb#L297-L311
train
david942j/memory_io
lib/memory_io/io.rb
MemoryIO.IO.write
def write(objects, from: nil, as: nil) stream.pos = from if from as ||= objects.class if objects.class.ancestors.include?(MemoryIO::Types::Type) return stream.write(objects) if as.nil? conv = to_proc(as, :write) Array(objects).map { |o| conv.call(stream, o) } end
ruby
def write(objects, from: nil, as: nil) stream.pos = from if from as ||= objects.class if objects.class.ancestors.include?(MemoryIO::Types::Type) return stream.write(objects) if as.nil? conv = to_proc(as, :write) Array(objects).map { |o| conv.call(stream, o) } end
[ "def", "write", "(", "objects", ",", "from", ":", "nil", ",", "as", ":", "nil", ")", "stream", ".", "pos", "=", "from", "if", "from", "as", "||=", "objects", ".", "class", "if", "objects", ".", "class", ".", "ancestors", ".", "include?", "(", "MemoryIO", "::", "Types", "::", "Type", ")", "return", "stream", ".", "write", "(", "objects", ")", "if", "as", ".", "nil?", "conv", "=", "to_proc", "(", "as", ",", ":write", ")", "Array", "(", "objects", ")", ".", "map", "{", "|", "o", "|", "conv", ".", "call", "(", "stream", ",", "o", ")", "}", "end" ]
Write to stream. @param [Object, Array<Object>] objects Objects to be written. @param [Integer] from The position to start to write. @param [nil, Symbol, Proc] as Decide the method to process writing procedure. See {MemoryIO::Types} for all supported types. A +Proc+ is allowed, which should accept +stream+ and one object as arguments. If +objects+ is a descendent instance of {Types::Type} and +as+ is +nil, +objects.class+ will be used for +as+. Otherwise, when +as = nil+, this method will simply call +stream.write(objects)+. @return [void] @example stream = StringIO.new io = MemoryIO::IO.new(stream) io.write('abcd') stream.string #=> "abcd" io.write([1, 2, 3, 4], from: 2, as: :u16) stream.string #=> "ab\x01\x00\x02\x00\x03\x00\x04\x00" io.write(['A', 'BB', 'CCC'], from: 0, as: :c_str) stream.string #=> "A\x00BB\x00CCC\x00\x00" @example stream = StringIO.new io = MemoryIO::IO.new(stream) io.write(%w[123 4567], as: ->(s, str) { s.write(str.size.chr + str) }) stream.string #=> "\x03123\x044567" @example stream = StringIO.new io = MemoryIO::IO.new(stream) cpp_string = CPP::String.new('A' * 4, 15, 16) # equivalent to io.write(cpp_string, as: :'cpp/string') io.write(cpp_string) stream.string #=> "\x10\x00\x00\x00\x00\x00\x00\x00\x04\x00\x00\x00\x00\x00\x00\x00AAAA\x00" @see Types
[ "Write", "to", "stream", "." ]
97a4206974b699767c57f3e113f78bdae69f950f
https://github.com/david942j/memory_io/blob/97a4206974b699767c57f3e113f78bdae69f950f/lib/memory_io/io.rb#L163-L170
train
david942j/memory_io
lib/memory_io/util.rb
MemoryIO.Util.underscore
def underscore(str) return '' if str.empty? str = str.gsub('::', '/') str.gsub!(/([A-Z]+)([A-Z][a-z])/, '\1_\2') str.gsub!(/([a-z\d])([A-Z])/, '\1_\2') str.downcase! str end
ruby
def underscore(str) return '' if str.empty? str = str.gsub('::', '/') str.gsub!(/([A-Z]+)([A-Z][a-z])/, '\1_\2') str.gsub!(/([a-z\d])([A-Z])/, '\1_\2') str.downcase! str end
[ "def", "underscore", "(", "str", ")", "return", "''", "if", "str", ".", "empty?", "str", "=", "str", ".", "gsub", "(", "'::'", ",", "'/'", ")", "str", ".", "gsub!", "(", "/", "/", ",", "'\\1_\\2'", ")", "str", ".", "gsub!", "(", "/", "\\d", "/", ",", "'\\1_\\2'", ")", "str", ".", "downcase!", "str", "end" ]
Convert input into snake-case. This method also converts +'::'+ to +'/'+. @param [String] str String to be converted. @return [String] Converted string. @example Util.underscore('MemoryIO') #=> 'memory_io' Util.underscore('MyModule::MyClass') #=> 'my_module/my_class'
[ "Convert", "input", "into", "snake", "-", "case", "." ]
97a4206974b699767c57f3e113f78bdae69f950f
https://github.com/david942j/memory_io/blob/97a4206974b699767c57f3e113f78bdae69f950f/lib/memory_io/util.rb#L25-L33
train
david942j/memory_io
lib/memory_io/util.rb
MemoryIO.Util.safe_eval
def safe_eval(str, **vars) return str if str.is_a?(Integer) # dentaku 2 doesn't support hex str = str.gsub(/0x[0-9a-zA-Z]+/) { |c| c.to_i(16) } Dentaku::Calculator.new.store(vars).evaluate(str) end
ruby
def safe_eval(str, **vars) return str if str.is_a?(Integer) # dentaku 2 doesn't support hex str = str.gsub(/0x[0-9a-zA-Z]+/) { |c| c.to_i(16) } Dentaku::Calculator.new.store(vars).evaluate(str) end
[ "def", "safe_eval", "(", "str", ",", "**", "vars", ")", "return", "str", "if", "str", ".", "is_a?", "(", "Integer", ")", "str", "=", "str", ".", "gsub", "(", "/", "/", ")", "{", "|", "c", "|", "c", ".", "to_i", "(", "16", ")", "}", "Dentaku", "::", "Calculator", ".", "new", ".", "store", "(", "vars", ")", ".", "evaluate", "(", "str", ")", "end" ]
Evaluate string safely. @param [String] str String to be evaluated. @param [{Symbol => Integer}] vars Predefined variables @return [Integer] Result. @example Util.safe_eval('heap + 0x10 * pp', heap: 0xde00, pp: 8) #=> 56960 # 0xde80
[ "Evaluate", "string", "safely", "." ]
97a4206974b699767c57f3e113f78bdae69f950f
https://github.com/david942j/memory_io/blob/97a4206974b699767c57f3e113f78bdae69f950f/lib/memory_io/util.rb#L75-L81
train
david942j/memory_io
lib/memory_io/util.rb
MemoryIO.Util.unpack
def unpack(str) str.bytes.reverse.reduce(0) { |s, c| s * 256 + c } end
ruby
def unpack(str) str.bytes.reverse.reduce(0) { |s, c| s * 256 + c } end
[ "def", "unpack", "(", "str", ")", "str", ".", "bytes", ".", "reverse", ".", "reduce", "(", "0", ")", "{", "|", "s", ",", "c", "|", "s", "*", "256", "+", "c", "}", "end" ]
Unpack a string into an integer. Little endian is used. @param [String] str String. @return [Integer] Result. @example Util.unpack("\xff") #=> 255 Util.unpack("@\xE2\x01\x00") #=> 123456
[ "Unpack", "a", "string", "into", "an", "integer", ".", "Little", "endian", "is", "used", "." ]
97a4206974b699767c57f3e113f78bdae69f950f
https://github.com/david942j/memory_io/blob/97a4206974b699767c57f3e113f78bdae69f950f/lib/memory_io/util.rb#L97-L99
train
david942j/memory_io
lib/memory_io/util.rb
MemoryIO.Util.pack
def pack(val, b) Array.new(b) { |i| (val >> (i * 8)) & 0xff }.pack('C*') end
ruby
def pack(val, b) Array.new(b) { |i| (val >> (i * 8)) & 0xff }.pack('C*') end
[ "def", "pack", "(", "val", ",", "b", ")", "Array", ".", "new", "(", "b", ")", "{", "|", "i", "|", "(", "val", ">>", "(", "i", "*", "8", ")", ")", "&", "0xff", "}", ".", "pack", "(", "'C*'", ")", "end" ]
Pack an integer into +b+ bytes. Little endian is used. @param [Integer] val The integer to pack. If +val+ contains more than +b+ bytes, only lower +b+ bytes in +val+ will be packed. @param [Integer] b @return [String] Packing result with length +b+. @example Util.pack(0x123, 4) #=> "\x23\x01\x00\x00"
[ "Pack", "an", "integer", "into", "+", "b", "+", "bytes", ".", "Little", "endian", "is", "used", "." ]
97a4206974b699767c57f3e113f78bdae69f950f
https://github.com/david942j/memory_io/blob/97a4206974b699767c57f3e113f78bdae69f950f/lib/memory_io/util.rb#L117-L119
train
oliamb/knnball
lib/knnball/kdtree.rb
KnnBall.KDTree.nearest
def nearest(coord, options = {}) return nil if root.nil? return nil if coord.nil? results = (options[:results] ? options[:results] : ResultSet.new({limit: options[:limit] || 1})) root_ball = options[:root] || root # keep the stack while finding the leaf best match. parents = [] best_balls = [] in_target = [] # Move down to best match current_best = nil current = root_ball while current_best.nil? dim = current.dimension-1 if(current.complete?) next_ball = (coord[dim] <= current.center[dim] ? current.left : current.right) elsif(current.leaf?) next_ball = nil else next_ball = (current.left.nil? ? current.right : current.left) end if ( next_ball.nil? ) current_best = current else parents.push current current = next_ball end end # Move up to check split parents.reverse! results.add(current_best.quick_distance(coord), current_best.value) parents.each do |current_node| dist = current_node.quick_distance(coord) if results.eligible?( dist ) results.add(dist, current_node.value) end dim = current_node.dimension-1 if current_node.complete? # retrieve the splitting node. split_node = (coord[dim] <= current_node.center[dim] ? current_node.right : current_node.left) best_dist = results.barrier_value if( (coord[dim] - current_node.center[dim]).abs <= best_dist) # potential match, need to investigate subtree nearest(coord, root: split_node, results: results) end end end return results.limit == 1 ? results.items.first : results.items end
ruby
def nearest(coord, options = {}) return nil if root.nil? return nil if coord.nil? results = (options[:results] ? options[:results] : ResultSet.new({limit: options[:limit] || 1})) root_ball = options[:root] || root # keep the stack while finding the leaf best match. parents = [] best_balls = [] in_target = [] # Move down to best match current_best = nil current = root_ball while current_best.nil? dim = current.dimension-1 if(current.complete?) next_ball = (coord[dim] <= current.center[dim] ? current.left : current.right) elsif(current.leaf?) next_ball = nil else next_ball = (current.left.nil? ? current.right : current.left) end if ( next_ball.nil? ) current_best = current else parents.push current current = next_ball end end # Move up to check split parents.reverse! results.add(current_best.quick_distance(coord), current_best.value) parents.each do |current_node| dist = current_node.quick_distance(coord) if results.eligible?( dist ) results.add(dist, current_node.value) end dim = current_node.dimension-1 if current_node.complete? # retrieve the splitting node. split_node = (coord[dim] <= current_node.center[dim] ? current_node.right : current_node.left) best_dist = results.barrier_value if( (coord[dim] - current_node.center[dim]).abs <= best_dist) # potential match, need to investigate subtree nearest(coord, root: split_node, results: results) end end end return results.limit == 1 ? results.items.first : results.items end
[ "def", "nearest", "(", "coord", ",", "options", "=", "{", "}", ")", "return", "nil", "if", "root", ".", "nil?", "return", "nil", "if", "coord", ".", "nil?", "results", "=", "(", "options", "[", ":results", "]", "?", "options", "[", ":results", "]", ":", "ResultSet", ".", "new", "(", "{", "limit", ":", "options", "[", ":limit", "]", "||", "1", "}", ")", ")", "root_ball", "=", "options", "[", ":root", "]", "||", "root", "parents", "=", "[", "]", "best_balls", "=", "[", "]", "in_target", "=", "[", "]", "current_best", "=", "nil", "current", "=", "root_ball", "while", "current_best", ".", "nil?", "dim", "=", "current", ".", "dimension", "-", "1", "if", "(", "current", ".", "complete?", ")", "next_ball", "=", "(", "coord", "[", "dim", "]", "<=", "current", ".", "center", "[", "dim", "]", "?", "current", ".", "left", ":", "current", ".", "right", ")", "elsif", "(", "current", ".", "leaf?", ")", "next_ball", "=", "nil", "else", "next_ball", "=", "(", "current", ".", "left", ".", "nil?", "?", "current", ".", "right", ":", "current", ".", "left", ")", "end", "if", "(", "next_ball", ".", "nil?", ")", "current_best", "=", "current", "else", "parents", ".", "push", "current", "current", "=", "next_ball", "end", "end", "parents", ".", "reverse!", "results", ".", "add", "(", "current_best", ".", "quick_distance", "(", "coord", ")", ",", "current_best", ".", "value", ")", "parents", ".", "each", "do", "|", "current_node", "|", "dist", "=", "current_node", ".", "quick_distance", "(", "coord", ")", "if", "results", ".", "eligible?", "(", "dist", ")", "results", ".", "add", "(", "dist", ",", "current_node", ".", "value", ")", "end", "dim", "=", "current_node", ".", "dimension", "-", "1", "if", "current_node", ".", "complete?", "split_node", "=", "(", "coord", "[", "dim", "]", "<=", "current_node", ".", "center", "[", "dim", "]", "?", "current_node", ".", "right", ":", "current_node", ".", "left", ")", "best_dist", "=", "results", ".", "barrier_value", "if", "(", "(", "coord", "[", "dim", "]", "-", "current_node", ".", "center", "[", "dim", "]", ")", ".", "abs", "<=", "best_dist", ")", "nearest", "(", "coord", ",", "root", ":", "split_node", ",", "results", ":", "results", ")", "end", "end", "end", "return", "results", ".", "limit", "==", "1", "?", "results", ".", "items", ".", "first", ":", "results", ".", "items", "end" ]
Retrieve the nearest point from the given coord array. available keys for options are :root and :limit Wikipedia tell us (excerpt from url http://en.wikipedia.org/wiki/Kd%5Ftree#Nearest%5Fneighbor%5Fsearch) Searching for a nearest neighbour in a k-d tree proceeds as follows: 1. Starting with the root node, the algorithm moves down the tree recursively, in the same way that it would if the search point were being inserted (i.e. it goes left or right depending on whether the point is less than or greater than the current node in the split dimension). 2. Once the algorithm reaches a leaf node, it saves that node point as the "current best" 3. The algorithm unwinds the recursion of the tree, performing the following steps at each node: 1. If the current node is closer than the current best, then it becomes the current best. 2. The algorithm checks whether there could be any points on the other side of the splitting plane that are closer to the search point than the current best. In concept, this is done by intersecting the splitting hyperplane with a hypersphere around the search point that has a radius equal to the current nearest distance. Since the hyperplanes are all axis-aligned this is implemented as a simple comparison to see whether the difference between the splitting coordinate of the search point and current node is less than the distance (overall coordinates) from the search point to the current best. 1. If the hypersphere crosses the plane, there could be nearer points on the other side of the plane, so the algorithm must move down the other branch of the tree from the current node looking for closer points, following the same recursive process as the entire search. 2. If the hypersphere doesn't intersect the splitting plane, then the algorithm continues walking up the tree, and the entire branch on the other side of that node is eliminated. 4. When the algorithm finishes this process for the root node, then the search is complete. Generally the algorithm uses squared distances for comparison to avoid computing square roots. Additionally, it can save computation by holding the squared current best distance in a variable for comparison.
[ "Retrieve", "the", "nearest", "point", "from", "the", "given", "coord", "array", "." ]
eb67c4452481d727ded06984ba7d82a92b5a8e03
https://github.com/oliamb/knnball/blob/eb67c4452481d727ded06984ba7d82a92b5a8e03/lib/knnball/kdtree.rb#L50-L104
train
oliamb/knnball
lib/knnball/kdtree.rb
KnnBall.KDTree.parent_ball
def parent_ball(coord) current = root d_idx = current.dimension-1 result = nil while(result.nil?) if(coord[d_idx] <= current.center[d_idx]) if current.left.nil? result = current else current = current.left end else if current.right.nil? result = current else current = current.right end end d_idx = current.dimension-1 end return result end
ruby
def parent_ball(coord) current = root d_idx = current.dimension-1 result = nil while(result.nil?) if(coord[d_idx] <= current.center[d_idx]) if current.left.nil? result = current else current = current.left end else if current.right.nil? result = current else current = current.right end end d_idx = current.dimension-1 end return result end
[ "def", "parent_ball", "(", "coord", ")", "current", "=", "root", "d_idx", "=", "current", ".", "dimension", "-", "1", "result", "=", "nil", "while", "(", "result", ".", "nil?", ")", "if", "(", "coord", "[", "d_idx", "]", "<=", "current", ".", "center", "[", "d_idx", "]", ")", "if", "current", ".", "left", ".", "nil?", "result", "=", "current", "else", "current", "=", "current", ".", "left", "end", "else", "if", "current", ".", "right", ".", "nil?", "result", "=", "current", "else", "current", "=", "current", ".", "right", "end", "end", "d_idx", "=", "current", ".", "dimension", "-", "1", "end", "return", "result", "end" ]
Retrieve the parent to which this coord should belongs to
[ "Retrieve", "the", "parent", "to", "which", "this", "coord", "should", "belongs", "to" ]
eb67c4452481d727ded06984ba7d82a92b5a8e03
https://github.com/oliamb/knnball/blob/eb67c4452481d727ded06984ba7d82a92b5a8e03/lib/knnball/kdtree.rb#L107-L128
train
matthin/teamspeak-ruby
lib/teamspeak-ruby/client.rb
Teamspeak.Client.command
def command(cmd, params = {}, options = '') flood_control out = '' response = '' out += cmd params.each_pair do |key, value| out += " #{key}=#{encode_param(value.to_s)}" end out += ' ' + options @sock.puts out if cmd == 'servernotifyregister' 2.times { response += @sock.gets } return parse_response(response) end loop do response += @sock.gets break if response.index(' msg=') end # Array of commands that are expected to return as an array. # Not sure - clientgetids should_be_array = %w( bindinglist serverlist servergrouplist servergroupclientlist servergroupsbyclientid servergroupclientlist logview channellist channelfind channelgrouplist channelgroupclientlist channelgrouppermlist channelpermlist clientlist clientfind clientdblist clientdbfind channelclientpermlist permissionlist permoverview privilegekeylist messagelist complainlist banlist ftlist custominfo permfind ) parsed_response = parse_response(response) should_be_array.include?(cmd) ? parsed_response : parsed_response.first end
ruby
def command(cmd, params = {}, options = '') flood_control out = '' response = '' out += cmd params.each_pair do |key, value| out += " #{key}=#{encode_param(value.to_s)}" end out += ' ' + options @sock.puts out if cmd == 'servernotifyregister' 2.times { response += @sock.gets } return parse_response(response) end loop do response += @sock.gets break if response.index(' msg=') end # Array of commands that are expected to return as an array. # Not sure - clientgetids should_be_array = %w( bindinglist serverlist servergrouplist servergroupclientlist servergroupsbyclientid servergroupclientlist logview channellist channelfind channelgrouplist channelgroupclientlist channelgrouppermlist channelpermlist clientlist clientfind clientdblist clientdbfind channelclientpermlist permissionlist permoverview privilegekeylist messagelist complainlist banlist ftlist custominfo permfind ) parsed_response = parse_response(response) should_be_array.include?(cmd) ? parsed_response : parsed_response.first end
[ "def", "command", "(", "cmd", ",", "params", "=", "{", "}", ",", "options", "=", "''", ")", "flood_control", "out", "=", "''", "response", "=", "''", "out", "+=", "cmd", "params", ".", "each_pair", "do", "|", "key", ",", "value", "|", "out", "+=", "\" #{key}=#{encode_param(value.to_s)}\"", "end", "out", "+=", "' '", "+", "options", "@sock", ".", "puts", "out", "if", "cmd", "==", "'servernotifyregister'", "2", ".", "times", "{", "response", "+=", "@sock", ".", "gets", "}", "return", "parse_response", "(", "response", ")", "end", "loop", "do", "response", "+=", "@sock", ".", "gets", "break", "if", "response", ".", "index", "(", "' msg='", ")", "end", "should_be_array", "=", "%w(", "bindinglist", "serverlist", "servergrouplist", "servergroupclientlist", "servergroupsbyclientid", "servergroupclientlist", "logview", "channellist", "channelfind", "channelgrouplist", "channelgroupclientlist", "channelgrouppermlist", "channelpermlist", "clientlist", "clientfind", "clientdblist", "clientdbfind", "channelclientpermlist", "permissionlist", "permoverview", "privilegekeylist", "messagelist", "complainlist", "banlist", "ftlist", "custominfo", "permfind", ")", "parsed_response", "=", "parse_response", "(", "response", ")", "should_be_array", ".", "include?", "(", "cmd", ")", "?", "parsed_response", ":", "parsed_response", ".", "first", "end" ]
Sends command to the TeamSpeak 3 server and returns the response command('use', {'sid' => 1}, '-away')
[ "Sends", "command", "to", "the", "TeamSpeak", "3", "server", "and", "returns", "the", "response" ]
a72ae0f9b1fdab013708dae1559361e280aac8a1
https://github.com/matthin/teamspeak-ruby/blob/a72ae0f9b1fdab013708dae1559361e280aac8a1/lib/teamspeak-ruby/client.rb#L76-L117
train
translationexchange/tml-rails
lib/tml_rails/extensions/action_view_extension.rb
TmlRails.ActionViewExtension.trh
def trh(tokens = {}, options = {}, &block) return '' unless block_given? label = capture(&block) tokenizer = Tml::Tokenizers::Dom.new(tokens, options) tokenizer.translate(label).html_safe end
ruby
def trh(tokens = {}, options = {}, &block) return '' unless block_given? label = capture(&block) tokenizer = Tml::Tokenizers::Dom.new(tokens, options) tokenizer.translate(label).html_safe end
[ "def", "trh", "(", "tokens", "=", "{", "}", ",", "options", "=", "{", "}", ",", "&", "block", ")", "return", "''", "unless", "block_given?", "label", "=", "capture", "(", "&", "block", ")", "tokenizer", "=", "Tml", "::", "Tokenizers", "::", "Dom", ".", "new", "(", "tokens", ",", "options", ")", "tokenizer", ".", "translate", "(", "label", ")", ".", "html_safe", "end" ]
Translates HTML block noinspection RubyArgCount
[ "Translates", "HTML", "block", "noinspection", "RubyArgCount" ]
6050b0e5f0ba1d64bb09b6356ac7e41782e949a5
https://github.com/translationexchange/tml-rails/blob/6050b0e5f0ba1d64bb09b6356ac7e41782e949a5/lib/tml_rails/extensions/action_view_extension.rb#L38-L45
train
translationexchange/tml-rails
lib/tml_rails/extensions/action_view_extension.rb
TmlRails.ActionViewExtension.tml_language_flag_tag
def tml_language_flag_tag(lang = tml_current_language, opts = {}) return '' unless tml_application.feature_enabled?(:language_flags) html = image_tag(lang.flag_url, :style => (opts[:style] || 'vertical-align:middle;'), :title => lang.native_name) html << '&nbsp;&nbsp;'.html_safe html.html_safe end
ruby
def tml_language_flag_tag(lang = tml_current_language, opts = {}) return '' unless tml_application.feature_enabled?(:language_flags) html = image_tag(lang.flag_url, :style => (opts[:style] || 'vertical-align:middle;'), :title => lang.native_name) html << '&nbsp;&nbsp;'.html_safe html.html_safe end
[ "def", "tml_language_flag_tag", "(", "lang", "=", "tml_current_language", ",", "opts", "=", "{", "}", ")", "return", "''", "unless", "tml_application", ".", "feature_enabled?", "(", ":language_flags", ")", "html", "=", "image_tag", "(", "lang", ".", "flag_url", ",", ":style", "=>", "(", "opts", "[", ":style", "]", "||", "'vertical-align:middle;'", ")", ",", ":title", "=>", "lang", ".", "native_name", ")", "html", "<<", "'&nbsp;&nbsp;'", ".", "html_safe", "html", ".", "html_safe", "end" ]
Returns language flag
[ "Returns", "language", "flag" ]
6050b0e5f0ba1d64bb09b6356ac7e41782e949a5
https://github.com/translationexchange/tml-rails/blob/6050b0e5f0ba1d64bb09b6356ac7e41782e949a5/lib/tml_rails/extensions/action_view_extension.rb#L53-L58
train
translationexchange/tml-rails
lib/tml_rails/extensions/action_view_extension.rb
TmlRails.ActionViewExtension.tml_language_name_tag
def tml_language_name_tag(lang = tml_current_language, opts = {}) show_flag = opts[:flag].nil? ? true : opts[:flag] name_type = opts[:language].nil? ? :english : opts[:language].to_sym # :full, :native, :english, :locale, :both html = [] html << "<span style='white-space: nowrap'>" html << tml_language_flag_tag(lang, opts) if show_flag html << "<span dir='ltr'>" if name_type == :both html << lang.english_name.to_s html << '<span class="trex-native-name">' html << lang.native_name html << '</span>' else name = case name_type when :native then lang.native_name when :full then lang.full_name when :locale then lang.locale else lang.english_name end html << name.to_s end html << '</span></span>' html.join.html_safe end
ruby
def tml_language_name_tag(lang = tml_current_language, opts = {}) show_flag = opts[:flag].nil? ? true : opts[:flag] name_type = opts[:language].nil? ? :english : opts[:language].to_sym # :full, :native, :english, :locale, :both html = [] html << "<span style='white-space: nowrap'>" html << tml_language_flag_tag(lang, opts) if show_flag html << "<span dir='ltr'>" if name_type == :both html << lang.english_name.to_s html << '<span class="trex-native-name">' html << lang.native_name html << '</span>' else name = case name_type when :native then lang.native_name when :full then lang.full_name when :locale then lang.locale else lang.english_name end html << name.to_s end html << '</span></span>' html.join.html_safe end
[ "def", "tml_language_name_tag", "(", "lang", "=", "tml_current_language", ",", "opts", "=", "{", "}", ")", "show_flag", "=", "opts", "[", ":flag", "]", ".", "nil?", "?", "true", ":", "opts", "[", ":flag", "]", "name_type", "=", "opts", "[", ":language", "]", ".", "nil?", "?", ":english", ":", "opts", "[", ":language", "]", ".", "to_sym", "html", "=", "[", "]", "html", "<<", "\"<span style='white-space: nowrap'>\"", "html", "<<", "tml_language_flag_tag", "(", "lang", ",", "opts", ")", "if", "show_flag", "html", "<<", "\"<span dir='ltr'>\"", "if", "name_type", "==", ":both", "html", "<<", "lang", ".", "english_name", ".", "to_s", "html", "<<", "'<span class=\"trex-native-name\">'", "html", "<<", "lang", ".", "native_name", "html", "<<", "'</span>'", "else", "name", "=", "case", "name_type", "when", ":native", "then", "lang", ".", "native_name", "when", ":full", "then", "lang", ".", "full_name", "when", ":locale", "then", "lang", ".", "locale", "else", "lang", ".", "english_name", "end", "html", "<<", "name", ".", "to_s", "end", "html", "<<", "'</span></span>'", "html", ".", "join", ".", "html_safe", "end" ]
Returns language name
[ "Returns", "language", "name" ]
6050b0e5f0ba1d64bb09b6356ac7e41782e949a5
https://github.com/translationexchange/tml-rails/blob/6050b0e5f0ba1d64bb09b6356ac7e41782e949a5/lib/tml_rails/extensions/action_view_extension.rb#L61-L87
train
translationexchange/tml-rails
lib/tml_rails/extensions/action_view_extension.rb
TmlRails.ActionViewExtension.tml_language_selector_tag
def tml_language_selector_tag(type = nil, opts = {}) return unless Tml.config.enabled? type ||= :default type = :dropdown if type == :select opts = opts.collect{|key, value| "data-tml-#{key}='#{value}'"}.join(' ') "<div data-tml-language-selector='#{type}' #{opts}></div>".html_safe end
ruby
def tml_language_selector_tag(type = nil, opts = {}) return unless Tml.config.enabled? type ||= :default type = :dropdown if type == :select opts = opts.collect{|key, value| "data-tml-#{key}='#{value}'"}.join(' ') "<div data-tml-language-selector='#{type}' #{opts}></div>".html_safe end
[ "def", "tml_language_selector_tag", "(", "type", "=", "nil", ",", "opts", "=", "{", "}", ")", "return", "unless", "Tml", ".", "config", ".", "enabled?", "type", "||=", ":default", "type", "=", ":dropdown", "if", "type", "==", ":select", "opts", "=", "opts", ".", "collect", "{", "|", "key", ",", "value", "|", "\"data-tml-#{key}='#{value}'\"", "}", ".", "join", "(", "' '", ")", "\"<div data-tml-language-selector='#{type}' #{opts}></div>\"", ".", "html_safe", "end" ]
Returns language selector UI
[ "Returns", "language", "selector", "UI" ]
6050b0e5f0ba1d64bb09b6356ac7e41782e949a5
https://github.com/translationexchange/tml-rails/blob/6050b0e5f0ba1d64bb09b6356ac7e41782e949a5/lib/tml_rails/extensions/action_view_extension.rb#L90-L98
train
translationexchange/tml-rails
lib/tml_rails/extensions/action_view_extension.rb
TmlRails.ActionViewExtension.tml_style_attribute_tag
def tml_style_attribute_tag(attr_name = 'float', default = 'right', lang = tml_current_language) return "#{attr_name}:#{default}".html_safe if Tml.config.disabled? "#{attr_name}:#{lang.align(default)}".html_safe end
ruby
def tml_style_attribute_tag(attr_name = 'float', default = 'right', lang = tml_current_language) return "#{attr_name}:#{default}".html_safe if Tml.config.disabled? "#{attr_name}:#{lang.align(default)}".html_safe end
[ "def", "tml_style_attribute_tag", "(", "attr_name", "=", "'float'", ",", "default", "=", "'right'", ",", "lang", "=", "tml_current_language", ")", "return", "\"#{attr_name}:#{default}\"", ".", "html_safe", "if", "Tml", ".", "config", ".", "disabled?", "\"#{attr_name}:#{lang.align(default)}\"", ".", "html_safe", "end" ]
Language Direction Support switches CSS positions based on the language direction <%= tml_style_attribute_tag('float', 'right') %> => "float: right" : "float: left" <%= tml_style_attribute_tag('align', 'right') %> => "align: right" : "align: left"
[ "Language", "Direction", "Support" ]
6050b0e5f0ba1d64bb09b6356ac7e41782e949a5
https://github.com/translationexchange/tml-rails/blob/6050b0e5f0ba1d64bb09b6356ac7e41782e949a5/lib/tml_rails/extensions/action_view_extension.rb#L232-L235
train
jferris/effigy
lib/effigy/example_element_transformer.rb
Effigy.ExampleElementTransformer.clone_and_transform_each
def clone_and_transform_each(collection, &block) collection.inject(element_to_clone) do |sibling, item| item_element = clone_with_item(item, &block) sibling.add_next_sibling(item_element) end end
ruby
def clone_and_transform_each(collection, &block) collection.inject(element_to_clone) do |sibling, item| item_element = clone_with_item(item, &block) sibling.add_next_sibling(item_element) end end
[ "def", "clone_and_transform_each", "(", "collection", ",", "&", "block", ")", "collection", ".", "inject", "(", "element_to_clone", ")", "do", "|", "sibling", ",", "item", "|", "item_element", "=", "clone_with_item", "(", "item", ",", "&", "block", ")", "sibling", ".", "add_next_sibling", "(", "item_element", ")", "end", "end" ]
Creates a clone for each item in the collection and yields it for transformation along with the corresponding item. The transformed clones are inserted after the element to clone. @param [Array] collection data that cloned elements should be transformed with @yield [Nokogiri::XML::Node] the cloned element @yield [Object] an item from the collection
[ "Creates", "a", "clone", "for", "each", "item", "in", "the", "collection", "and", "yields", "it", "for", "transformation", "along", "with", "the", "corresponding", "item", ".", "The", "transformed", "clones", "are", "inserted", "after", "the", "element", "to", "clone", "." ]
366ad3571b0fc81f681472eb0ae911f47c60a405
https://github.com/jferris/effigy/blob/366ad3571b0fc81f681472eb0ae911f47c60a405/lib/effigy/example_element_transformer.rb#L35-L40
train
jferris/effigy
lib/effigy/example_element_transformer.rb
Effigy.ExampleElementTransformer.clone_with_item
def clone_with_item(item, &block) item_element = element_to_clone.dup view.find(item_element) { yield(item) } item_element end
ruby
def clone_with_item(item, &block) item_element = element_to_clone.dup view.find(item_element) { yield(item) } item_element end
[ "def", "clone_with_item", "(", "item", ",", "&", "block", ")", "item_element", "=", "element_to_clone", ".", "dup", "view", ".", "find", "(", "item_element", ")", "{", "yield", "(", "item", ")", "}", "item_element", "end" ]
Creates a clone and yields it to the given block along with the given item. @param [Object] item the item to use with the clone @yield [Nokogiri::XML:Node] the cloned node @yield [Object] the given item @return [Nokogiri::XML::Node] the transformed clone
[ "Creates", "a", "clone", "and", "yields", "it", "to", "the", "given", "block", "along", "with", "the", "given", "item", "." ]
366ad3571b0fc81f681472eb0ae911f47c60a405
https://github.com/jferris/effigy/blob/366ad3571b0fc81f681472eb0ae911f47c60a405/lib/effigy/example_element_transformer.rb#L57-L61
train
jferris/effigy
lib/effigy/view.rb
Effigy.View.text
def text(selector, content) select(selector).each do |node| node.content = content end end
ruby
def text(selector, content) select(selector).each do |node| node.content = content end end
[ "def", "text", "(", "selector", ",", "content", ")", "select", "(", "selector", ")", ".", "each", "do", "|", "node", "|", "node", ".", "content", "=", "content", "end", "end" ]
Replaces the text content of the selected elements. Markup in the given content is escaped. Use {#html} if you want to replace the contents with live markup. @param [String] selector a CSS or XPath string describing the elements to transform @param [String] content the text that should be the new contents @example text('h1', 'a title') find('h1').text('a title') text('p', '<b>title</b>') # <p>&lt;b&gt;title&lt;/title&gt;</p>
[ "Replaces", "the", "text", "content", "of", "the", "selected", "elements", "." ]
366ad3571b0fc81f681472eb0ae911f47c60a405
https://github.com/jferris/effigy/blob/366ad3571b0fc81f681472eb0ae911f47c60a405/lib/effigy/view.rb#L38-L42
train
jferris/effigy
lib/effigy/view.rb
Effigy.View.attr
def attr(selector, attributes_or_attribute_name, value = nil) attributes = attributes_or_attribute_name.to_effigy_attributes(value) select(selector).each do |element| element.merge!(attributes) end end
ruby
def attr(selector, attributes_or_attribute_name, value = nil) attributes = attributes_or_attribute_name.to_effigy_attributes(value) select(selector).each do |element| element.merge!(attributes) end end
[ "def", "attr", "(", "selector", ",", "attributes_or_attribute_name", ",", "value", "=", "nil", ")", "attributes", "=", "attributes_or_attribute_name", ".", "to_effigy_attributes", "(", "value", ")", "select", "(", "selector", ")", ".", "each", "do", "|", "element", "|", "element", ".", "merge!", "(", "attributes", ")", "end", "end" ]
Adds or updates the given attribute or attributes of the selected elements. @param [String] selector a CSS or XPath string describing the elements to transform @param [String,Hash] attributes_or_attribute_name if a String, replaces that attribute with the given value. If a Hash, uses the keys as attribute names and values as attribute values @param [String] value the value for the replaced attribute. Used only if attributes_or_attribute_name is a String @example attr('p', :id => 'an_id', :style => 'display: none') attr('p', :id, 'an_id') find('p').attr(:id, 'an_id')
[ "Adds", "or", "updates", "the", "given", "attribute", "or", "attributes", "of", "the", "selected", "elements", "." ]
366ad3571b0fc81f681472eb0ae911f47c60a405
https://github.com/jferris/effigy/blob/366ad3571b0fc81f681472eb0ae911f47c60a405/lib/effigy/view.rb#L57-L62
train
jferris/effigy
lib/effigy/view.rb
Effigy.View.replace_each
def replace_each(selector, collection, &block) selected_elements = select(selector) ExampleElementTransformer.new(self, selected_elements).replace_each(collection, &block) end
ruby
def replace_each(selector, collection, &block) selected_elements = select(selector) ExampleElementTransformer.new(self, selected_elements).replace_each(collection, &block) end
[ "def", "replace_each", "(", "selector", ",", "collection", ",", "&", "block", ")", "selected_elements", "=", "select", "(", "selector", ")", "ExampleElementTransformer", ".", "new", "(", "self", ",", "selected_elements", ")", ".", "replace_each", "(", "collection", ",", "&", "block", ")", "end" ]
Replaces the selected elements with a clone for each item in the collection. If multiple elements are selected, only the first element will be used for cloning. All selected elements will be removed. @param [String] selector a CSS or XPath string describing the elements to transform @param [Enumerable] collection the items that are the base for each cloned element @example titles = %w(one two three) find('.post').replace_each(titles) do |title| text('h1', title) end
[ "Replaces", "the", "selected", "elements", "with", "a", "clone", "for", "each", "item", "in", "the", "collection", ".", "If", "multiple", "elements", "are", "selected", "only", "the", "first", "element", "will", "be", "used", "for", "cloning", ".", "All", "selected", "elements", "will", "be", "removed", "." ]
366ad3571b0fc81f681472eb0ae911f47c60a405
https://github.com/jferris/effigy/blob/366ad3571b0fc81f681472eb0ae911f47c60a405/lib/effigy/view.rb#L77-L80
train
jferris/effigy
lib/effigy/view.rb
Effigy.View.add_class
def add_class(selector, *class_names) select(selector).each do |element| class_list = ClassList.new(element) class_list.add class_names end end
ruby
def add_class(selector, *class_names) select(selector).each do |element| class_list = ClassList.new(element) class_list.add class_names end end
[ "def", "add_class", "(", "selector", ",", "*", "class_names", ")", "select", "(", "selector", ")", ".", "each", "do", "|", "element", "|", "class_list", "=", "ClassList", ".", "new", "(", "element", ")", "class_list", ".", "add", "class_names", "end", "end" ]
Adds the given class names to the selected elements. @param [String] selector a CSS or XPath string describing the elements to transform @param [String] class_names a CSS class name that should be added @example add_class('a#home', 'selected') find('a#home').add_class('selected')
[ "Adds", "the", "given", "class", "names", "to", "the", "selected", "elements", "." ]
366ad3571b0fc81f681472eb0ae911f47c60a405
https://github.com/jferris/effigy/blob/366ad3571b0fc81f681472eb0ae911f47c60a405/lib/effigy/view.rb#L123-L128
train
jferris/effigy
lib/effigy/view.rb
Effigy.View.remove_class
def remove_class(selector, *class_names) select(selector).each do |element| class_list = ClassList.new(element) class_list.remove(class_names) end end
ruby
def remove_class(selector, *class_names) select(selector).each do |element| class_list = ClassList.new(element) class_list.remove(class_names) end end
[ "def", "remove_class", "(", "selector", ",", "*", "class_names", ")", "select", "(", "selector", ")", ".", "each", "do", "|", "element", "|", "class_list", "=", "ClassList", ".", "new", "(", "element", ")", "class_list", ".", "remove", "(", "class_names", ")", "end", "end" ]
Removes the given class names from the selected elements. Ignores class names that are not present. @param [String] selector a CSS or XPath string describing the elements to transform @param [String] class_names a CSS class name that should be removed @example remove_class('a#home', 'selected') find('a#home').remove_class('selected')
[ "Removes", "the", "given", "class", "names", "from", "the", "selected", "elements", "." ]
366ad3571b0fc81f681472eb0ae911f47c60a405
https://github.com/jferris/effigy/blob/366ad3571b0fc81f681472eb0ae911f47c60a405/lib/effigy/view.rb#L140-L145
train
jferris/effigy
lib/effigy/view.rb
Effigy.View.html
def html(selector, inner_html) select(selector).each do |node| node.inner_html = inner_html end end
ruby
def html(selector, inner_html) select(selector).each do |node| node.inner_html = inner_html end end
[ "def", "html", "(", "selector", ",", "inner_html", ")", "select", "(", "selector", ")", ".", "each", "do", "|", "node", "|", "node", ".", "inner_html", "=", "inner_html", "end", "end" ]
Replaces the contents of the selected elements with live markup. @param [String] selector a CSS or XPath string describing the elements to transform @param [String] inner_html the new contents of the selected elements. Markup is @example html('p', '<b>Welcome!</b>') find('p').html('<b>Welcome!</b>')
[ "Replaces", "the", "contents", "of", "the", "selected", "elements", "with", "live", "markup", "." ]
366ad3571b0fc81f681472eb0ae911f47c60a405
https://github.com/jferris/effigy/blob/366ad3571b0fc81f681472eb0ae911f47c60a405/lib/effigy/view.rb#L155-L159
train
jferris/effigy
lib/effigy/view.rb
Effigy.View.append
def append(selector, html_to_append) select(selector).each { |node| node.append_fragment html_to_append } end
ruby
def append(selector, html_to_append) select(selector).each { |node| node.append_fragment html_to_append } end
[ "def", "append", "(", "selector", ",", "html_to_append", ")", "select", "(", "selector", ")", ".", "each", "{", "|", "node", "|", "node", ".", "append_fragment", "html_to_append", "}", "end" ]
Adds the given markup to the end of the selected elements. @param [String] selector a CSS or XPath string describing the elements to which this HTML should be appended @param [String] html_to_append the new markup to append to the selected element. Markup is not escaped.
[ "Adds", "the", "given", "markup", "to", "the", "end", "of", "the", "selected", "elements", "." ]
366ad3571b0fc81f681472eb0ae911f47c60a405
https://github.com/jferris/effigy/blob/366ad3571b0fc81f681472eb0ae911f47c60a405/lib/effigy/view.rb#L179-L181
train
jferris/effigy
lib/effigy/view.rb
Effigy.View.find
def find(selector) if block_given? old_context = @current_context @current_context = select(selector) yield @current_context = old_context else Selection.new(self, selector) end end
ruby
def find(selector) if block_given? old_context = @current_context @current_context = select(selector) yield @current_context = old_context else Selection.new(self, selector) end end
[ "def", "find", "(", "selector", ")", "if", "block_given?", "old_context", "=", "@current_context", "@current_context", "=", "select", "(", "selector", ")", "yield", "@current_context", "=", "old_context", "else", "Selection", ".", "new", "(", "self", ",", "selector", ")", "end", "end" ]
Selects an element or elements for chained transformation. If given a block, the selection will be in effect during the block. If not given a block, a {Selection} will be returned on which transformation methods can be called. Any methods called on the Selection will be delegated back to the view with the selector inserted into the parameter list. @param [String] selector a CSS or XPath string describing the element to transform @return [Selection] a proxy object on which transformation methods can be called @example find('.post') do text('h1', post.title) text('p', post.body) end find('h1').text(post.title).add_class('active')
[ "Selects", "an", "element", "or", "elements", "for", "chained", "transformation", "." ]
366ad3571b0fc81f681472eb0ae911f47c60a405
https://github.com/jferris/effigy/blob/366ad3571b0fc81f681472eb0ae911f47c60a405/lib/effigy/view.rb#L202-L211
train
jferris/effigy
lib/effigy/view.rb
Effigy.View.clone_element_with_item
def clone_element_with_item(original_element, item, &block) item_element = original_element.dup find(item_element) { yield(item) } item_element end
ruby
def clone_element_with_item(original_element, item, &block) item_element = original_element.dup find(item_element) { yield(item) } item_element end
[ "def", "clone_element_with_item", "(", "original_element", ",", "item", ",", "&", "block", ")", "item_element", "=", "original_element", ".", "dup", "find", "(", "item_element", ")", "{", "yield", "(", "item", ")", "}", "item_element", "end" ]
Clones an element, sets it as the current context, and yields to the given block with the given item. @param [Nokogiri::HTML::Element] the element to clone @param [Object] item the item that should be yielded to the block @yield [Object] the item passed as item @return [Nokogiri::HTML::Element] the clone of the original element
[ "Clones", "an", "element", "sets", "it", "as", "the", "current", "context", "and", "yields", "to", "the", "given", "block", "with", "the", "given", "item", "." ]
366ad3571b0fc81f681472eb0ae911f47c60a405
https://github.com/jferris/effigy/blob/366ad3571b0fc81f681472eb0ae911f47c60a405/lib/effigy/view.rb#L265-L269
train
movitto/reterm
lib/reterm/mixins/component_input.rb
RETerm.ComponentInput.handle_input
def handle_input(*input) while ch = next_ch(input) quit = QUIT_CONTROLS.include?(ch) enter = ENTER_CONTROLS.include?(ch) inc = INC_CONTROLS.include?(ch) dec = DEC_CONTROLS.include?(ch) break if shutdown? || (quit && (!enter || quit_on_enter?)) if enter on_enter elsif inc on_inc elsif dec on_dec end if key_bound?(ch) invoke_key_bindings(ch) end on_key(ch) end ch end
ruby
def handle_input(*input) while ch = next_ch(input) quit = QUIT_CONTROLS.include?(ch) enter = ENTER_CONTROLS.include?(ch) inc = INC_CONTROLS.include?(ch) dec = DEC_CONTROLS.include?(ch) break if shutdown? || (quit && (!enter || quit_on_enter?)) if enter on_enter elsif inc on_inc elsif dec on_dec end if key_bound?(ch) invoke_key_bindings(ch) end on_key(ch) end ch end
[ "def", "handle_input", "(", "*", "input", ")", "while", "ch", "=", "next_ch", "(", "input", ")", "quit", "=", "QUIT_CONTROLS", ".", "include?", "(", "ch", ")", "enter", "=", "ENTER_CONTROLS", ".", "include?", "(", "ch", ")", "inc", "=", "INC_CONTROLS", ".", "include?", "(", "ch", ")", "dec", "=", "DEC_CONTROLS", ".", "include?", "(", "ch", ")", "break", "if", "shutdown?", "||", "(", "quit", "&&", "(", "!", "enter", "||", "quit_on_enter?", ")", ")", "if", "enter", "on_enter", "elsif", "inc", "on_inc", "elsif", "dec", "on_dec", "end", "if", "key_bound?", "(", "ch", ")", "invoke_key_bindings", "(", "ch", ")", "end", "on_key", "(", "ch", ")", "end", "ch", "end" ]
Helper to be internally invoked by component on activation
[ "Helper", "to", "be", "internally", "invoked", "by", "component", "on", "activation" ]
3e78c64e677f69b22f00dc89c2b515b9188c5e15
https://github.com/movitto/reterm/blob/3e78c64e677f69b22f00dc89c2b515b9188c5e15/lib/reterm/mixins/component_input.rb#L32-L60
train
shanebdavis/Babel-Bridge
lib/babel_bridge/nodes/rule_node.rb
BabelBridge.RuleNode.match
def match(pattern_element) @num_match_attempts += 1 return :no_pattern_element unless pattern_element return :skipped if pattern_element.delimiter && ( if last_match last_match.delimiter # don't match two delimiters in a row else @num_match_attempts > 1 # don't match a delimiter as the first element unless this is the first match attempt end ) if result = pattern_element.parse(self) add_match result, pattern_element.name # success, but don't keep EmptyNodes end end
ruby
def match(pattern_element) @num_match_attempts += 1 return :no_pattern_element unless pattern_element return :skipped if pattern_element.delimiter && ( if last_match last_match.delimiter # don't match two delimiters in a row else @num_match_attempts > 1 # don't match a delimiter as the first element unless this is the first match attempt end ) if result = pattern_element.parse(self) add_match result, pattern_element.name # success, but don't keep EmptyNodes end end
[ "def", "match", "(", "pattern_element", ")", "@num_match_attempts", "+=", "1", "return", ":no_pattern_element", "unless", "pattern_element", "return", ":skipped", "if", "pattern_element", ".", "delimiter", "&&", "(", "if", "last_match", "last_match", ".", "delimiter", "else", "@num_match_attempts", ">", "1", "end", ")", "if", "result", "=", "pattern_element", ".", "parse", "(", "self", ")", "add_match", "result", ",", "pattern_element", ".", "name", "end", "end" ]
Attempts to match the pattern_element starting at the end of what has already been matched If successful, adds the resulting Node to matches. returns nil on if pattern_element wasn't matched; non-nil if it was skipped or matched
[ "Attempts", "to", "match", "the", "pattern_element", "starting", "at", "the", "end", "of", "what", "has", "already", "been", "matched", "If", "successful", "adds", "the", "resulting", "Node", "to", "matches", ".", "returns", "nil", "on", "if", "pattern_element", "wasn", "t", "matched", ";", "non", "-", "nil", "if", "it", "was", "skipped", "or", "matched" ]
415c6be1e3002b5eec96a8f1e3bcc7769eb29a57
https://github.com/shanebdavis/Babel-Bridge/blob/415c6be1e3002b5eec96a8f1e3bcc7769eb29a57/lib/babel_bridge/nodes/rule_node.rb#L113-L128
train
shanebdavis/Babel-Bridge
lib/babel_bridge/nodes/rule_node.rb
BabelBridge.RuleNode.attempt_match
def attempt_match matches_before = matches.length match_length_before = match_length (yield && match_length > match_length_before).tap do |success| # match_length test returns failure if no progress is made (our source position isn't advanced) unless success @matches = matches[0..matches_before-1] update_match_length end end end
ruby
def attempt_match matches_before = matches.length match_length_before = match_length (yield && match_length > match_length_before).tap do |success| # match_length test returns failure if no progress is made (our source position isn't advanced) unless success @matches = matches[0..matches_before-1] update_match_length end end end
[ "def", "attempt_match", "matches_before", "=", "matches", ".", "length", "match_length_before", "=", "match_length", "(", "yield", "&&", "match_length", ">", "match_length_before", ")", ".", "tap", "do", "|", "success", "|", "unless", "success", "@matches", "=", "matches", "[", "0", "..", "matches_before", "-", "1", "]", "update_match_length", "end", "end", "end" ]
a simple "transaction" - logs the curent number of matches, if the block's result is false, it discards all new matches
[ "a", "simple", "transaction", "-", "logs", "the", "curent", "number", "of", "matches", "if", "the", "block", "s", "result", "is", "false", "it", "discards", "all", "new", "matches" ]
415c6be1e3002b5eec96a8f1e3bcc7769eb29a57
https://github.com/shanebdavis/Babel-Bridge/blob/415c6be1e3002b5eec96a8f1e3bcc7769eb29a57/lib/babel_bridge/nodes/rule_node.rb#L143-L152
train
dburkes/people_places_things
lib/people_places_things/street_address.rb
PeoplePlacesThings.StreetAddress.to_canonical_s
def to_canonical_s parts = [] parts << self.number.upcase if self.number parts << StreetAddress.string_for(self.pre_direction, :short).upcase if self.pre_direction parts << StreetAddress.string_for(StreetAddress.find_token(self.ordinal, ORDINALS), :short).upcase if self.ordinal canonical_name = self.name.gsub(/[(,?!\'":.#)]/, '').gsub(PO_BOX_PATTERN, 'PO BOX').upcase if self.name canonical_name.gsub!(/(rr|r.r.)/i, 'RR') if canonical_name =~ RR_PATTERN # remove the original ordinal and box from the name, they are output in canonical form separately canonical_name.gsub!(self.ordinal.upcase, '') if self.ordinal canonical_name.gsub!(self.box_number, '') if self.box_number parts << canonical_name.chomp(' ') if canonical_name parts << self.box_number if self.box_number parts << StreetAddress.string_for(self.suffix, :short).upcase if self.suffix parts << StreetAddress.string_for(self.post_direction, :short).upcase if self.post_direction # make all unit type as the canoncial number "#" parts << StreetAddress.string_for(:number, :short).upcase if self.unit_type parts << self.unit.upcase if self.unit parts.delete('') parts.join(' ') end
ruby
def to_canonical_s parts = [] parts << self.number.upcase if self.number parts << StreetAddress.string_for(self.pre_direction, :short).upcase if self.pre_direction parts << StreetAddress.string_for(StreetAddress.find_token(self.ordinal, ORDINALS), :short).upcase if self.ordinal canonical_name = self.name.gsub(/[(,?!\'":.#)]/, '').gsub(PO_BOX_PATTERN, 'PO BOX').upcase if self.name canonical_name.gsub!(/(rr|r.r.)/i, 'RR') if canonical_name =~ RR_PATTERN # remove the original ordinal and box from the name, they are output in canonical form separately canonical_name.gsub!(self.ordinal.upcase, '') if self.ordinal canonical_name.gsub!(self.box_number, '') if self.box_number parts << canonical_name.chomp(' ') if canonical_name parts << self.box_number if self.box_number parts << StreetAddress.string_for(self.suffix, :short).upcase if self.suffix parts << StreetAddress.string_for(self.post_direction, :short).upcase if self.post_direction # make all unit type as the canoncial number "#" parts << StreetAddress.string_for(:number, :short).upcase if self.unit_type parts << self.unit.upcase if self.unit parts.delete('') parts.join(' ') end
[ "def", "to_canonical_s", "parts", "=", "[", "]", "parts", "<<", "self", ".", "number", ".", "upcase", "if", "self", ".", "number", "parts", "<<", "StreetAddress", ".", "string_for", "(", "self", ".", "pre_direction", ",", ":short", ")", ".", "upcase", "if", "self", ".", "pre_direction", "parts", "<<", "StreetAddress", ".", "string_for", "(", "StreetAddress", ".", "find_token", "(", "self", ".", "ordinal", ",", "ORDINALS", ")", ",", ":short", ")", ".", "upcase", "if", "self", ".", "ordinal", "canonical_name", "=", "self", ".", "name", ".", "gsub", "(", "/", "\\'", "/", ",", "''", ")", ".", "gsub", "(", "PO_BOX_PATTERN", ",", "'PO BOX'", ")", ".", "upcase", "if", "self", ".", "name", "canonical_name", ".", "gsub!", "(", "/", "/i", ",", "'RR'", ")", "if", "canonical_name", "=~", "RR_PATTERN", "canonical_name", ".", "gsub!", "(", "self", ".", "ordinal", ".", "upcase", ",", "''", ")", "if", "self", ".", "ordinal", "canonical_name", ".", "gsub!", "(", "self", ".", "box_number", ",", "''", ")", "if", "self", ".", "box_number", "parts", "<<", "canonical_name", ".", "chomp", "(", "' '", ")", "if", "canonical_name", "parts", "<<", "self", ".", "box_number", "if", "self", ".", "box_number", "parts", "<<", "StreetAddress", ".", "string_for", "(", "self", ".", "suffix", ",", ":short", ")", ".", "upcase", "if", "self", ".", "suffix", "parts", "<<", "StreetAddress", ".", "string_for", "(", "self", ".", "post_direction", ",", ":short", ")", ".", "upcase", "if", "self", ".", "post_direction", "parts", "<<", "StreetAddress", ".", "string_for", "(", ":number", ",", ":short", ")", ".", "upcase", "if", "self", ".", "unit_type", "parts", "<<", "self", ".", "unit", ".", "upcase", "if", "self", ".", "unit", "parts", ".", "delete", "(", "''", ")", "parts", ".", "join", "(", "' '", ")", "end" ]
to_canonical_s format the address in a postal service canonical format
[ "to_canonical_s", "format", "the", "address", "in", "a", "postal", "service", "canonical", "format" ]
69d18c0f236e40701fe58fa0d14e0dee03c879fc
https://github.com/dburkes/people_places_things/blob/69d18c0f236e40701fe58fa0d14e0dee03c879fc/lib/people_places_things/street_address.rb#L99-L118
train
kevgo/active_cucumber
lib/active_cucumber/cucumparer.rb
ActiveCucumber.Cucumparer.to_horizontal_table
def to_horizontal_table mortadella = Mortadella::Horizontal.new headers: @cucumber_table.headers @database_content = @database_content.all if @database_content.respond_to? :all @database_content.each do |record| cucumberator = cucumberator_for record mortadella << @cucumber_table.headers.map do |header| cucumberator.value_for header end end mortadella.table end
ruby
def to_horizontal_table mortadella = Mortadella::Horizontal.new headers: @cucumber_table.headers @database_content = @database_content.all if @database_content.respond_to? :all @database_content.each do |record| cucumberator = cucumberator_for record mortadella << @cucumber_table.headers.map do |header| cucumberator.value_for header end end mortadella.table end
[ "def", "to_horizontal_table", "mortadella", "=", "Mortadella", "::", "Horizontal", ".", "new", "headers", ":", "@cucumber_table", ".", "headers", "@database_content", "=", "@database_content", ".", "all", "if", "@database_content", ".", "respond_to?", ":all", "@database_content", ".", "each", "do", "|", "record", "|", "cucumberator", "=", "cucumberator_for", "record", "mortadella", "<<", "@cucumber_table", ".", "headers", ".", "map", "do", "|", "header", "|", "cucumberator", ".", "value_for", "header", "end", "end", "mortadella", ".", "table", "end" ]
Returns all entries in the database as a horizontal Mortadella table
[ "Returns", "all", "entries", "in", "the", "database", "as", "a", "horizontal", "Mortadella", "table" ]
9f3609abbfe2c4c3534c2c64d2f638a6bb6347cf
https://github.com/kevgo/active_cucumber/blob/9f3609abbfe2c4c3534c2c64d2f638a6bb6347cf/lib/active_cucumber/cucumparer.rb#L12-L22
train
kevgo/active_cucumber
lib/active_cucumber/cucumparer.rb
ActiveCucumber.Cucumparer.to_vertical_table
def to_vertical_table object mortadella = Mortadella::Vertical.new cucumberator = cucumberator_for object @cucumber_table.rows_hash.each do |key, _| mortadella[key] = cucumberator.value_for key end mortadella.table end
ruby
def to_vertical_table object mortadella = Mortadella::Vertical.new cucumberator = cucumberator_for object @cucumber_table.rows_hash.each do |key, _| mortadella[key] = cucumberator.value_for key end mortadella.table end
[ "def", "to_vertical_table", "object", "mortadella", "=", "Mortadella", "::", "Vertical", ".", "new", "cucumberator", "=", "cucumberator_for", "object", "@cucumber_table", ".", "rows_hash", ".", "each", "do", "|", "key", ",", "_", "|", "mortadella", "[", "key", "]", "=", "cucumberator", ".", "value_for", "key", "end", "mortadella", ".", "table", "end" ]
Returns the given object as a vertical Mortadella table
[ "Returns", "the", "given", "object", "as", "a", "vertical", "Mortadella", "table" ]
9f3609abbfe2c4c3534c2c64d2f638a6bb6347cf
https://github.com/kevgo/active_cucumber/blob/9f3609abbfe2c4c3534c2c64d2f638a6bb6347cf/lib/active_cucumber/cucumparer.rb#L25-L32
train
coopernurse/barrister-ruby
lib/barrister.rb
Barrister.Server.handle_json
def handle_json(json_str) begin req = JSON::parse(json_str) resp = handle(req) rescue JSON::ParserError => e resp = err_resp({ }, -32700, "Unable to parse JSON: #{e.message}") end # Note the `:ascii_only` usage here. Important. return JSON::generate(resp, { :ascii_only=>true }) end
ruby
def handle_json(json_str) begin req = JSON::parse(json_str) resp = handle(req) rescue JSON::ParserError => e resp = err_resp({ }, -32700, "Unable to parse JSON: #{e.message}") end # Note the `:ascii_only` usage here. Important. return JSON::generate(resp, { :ascii_only=>true }) end
[ "def", "handle_json", "(", "json_str", ")", "begin", "req", "=", "JSON", "::", "parse", "(", "json_str", ")", "resp", "=", "handle", "(", "req", ")", "rescue", "JSON", "::", "ParserError", "=>", "e", "resp", "=", "err_resp", "(", "{", "}", ",", "-", "32700", ",", "\"Unable to parse JSON: #{e.message}\"", ")", "end", "return", "JSON", "::", "generate", "(", "resp", ",", "{", ":ascii_only", "=>", "true", "}", ")", "end" ]
Handles a request encoded as JSON. Returns the result as a JSON encoded string.
[ "Handles", "a", "request", "encoded", "as", "JSON", ".", "Returns", "the", "result", "as", "a", "JSON", "encoded", "string", "." ]
5606e7dc591762fc28a338dee48093aaaafb106e
https://github.com/coopernurse/barrister-ruby/blob/5606e7dc591762fc28a338dee48093aaaafb106e/lib/barrister.rb#L165-L175
train
coopernurse/barrister-ruby
lib/barrister.rb
Barrister.Server.handle
def handle(req) if req.kind_of?(Array) resp_list = [ ] req.each do |r| resp_list << handle_single(r) end return resp_list else return handle_single(req) end end
ruby
def handle(req) if req.kind_of?(Array) resp_list = [ ] req.each do |r| resp_list << handle_single(r) end return resp_list else return handle_single(req) end end
[ "def", "handle", "(", "req", ")", "if", "req", ".", "kind_of?", "(", "Array", ")", "resp_list", "=", "[", "]", "req", ".", "each", "do", "|", "r", "|", "resp_list", "<<", "handle_single", "(", "r", ")", "end", "return", "resp_list", "else", "return", "handle_single", "(", "req", ")", "end", "end" ]
Handles a deserialized request and returns the result `req` must either be a Hash (single request), or an Array (batch request) `handle` returns an Array of results for batch requests, and a single Hash for single requests.
[ "Handles", "a", "deserialized", "request", "and", "returns", "the", "result" ]
5606e7dc591762fc28a338dee48093aaaafb106e
https://github.com/coopernurse/barrister-ruby/blob/5606e7dc591762fc28a338dee48093aaaafb106e/lib/barrister.rb#L183-L193
train
coopernurse/barrister-ruby
lib/barrister.rb
Barrister.Server.handle_single
def handle_single(req) method = req["method"] if !method return err_resp(req, -32600, "No method provided on request") end # Special case - client is requesting the IDL bound to this server, so # we return it verbatim. No further validation is needed in this case. if method == "barrister-idl" return ok_resp(req, @contract.idl) end # Make sure we can find an interface and function on the IDL for this # request method string err_resp, iface, func = @contract.resolve_method(req) if err_resp != nil return err_resp end # Make sure that the params on the request match the IDL types err_resp = @contract.validate_params(req, func) if err_resp != nil return err_resp end params = [ ] if req["params"] params = req["params"] end # Make sure we have a handler bound to this Server for the interface. # If not, that means `server.add_handler` was not called for this interface # name. That's likely a misconfiguration. handler = @handlers[iface.name] if !handler return err_resp(req, -32000, "Server error. No handler is bound to interface #{iface.name}") end # Make sure that the handler has a method for the given function. if !handler.respond_to?(func.name) return err_resp(req, -32000, "Server error. Handler for #{iface.name} does not implement #{func.name}") end begin # Call the handler function. This is where your code gets invoked. result = handler.send(func.name, *params) # Verify that the handler function's return value matches the # correct type as specified in the IDL err_resp = @contract.validate_result(req, result, func) if err_resp != nil return err_resp else return ok_resp(req, result) end rescue RpcException => e # If the handler raised a RpcException, that's ok - return it unmodified. return err_resp(req, e.code, e.message, e.data) rescue => e # If any other error was raised, print it and return a generic error to the client puts e.inspect puts e.backtrace return err_resp(req, -32000, "Unknown error: #{e}") end end
ruby
def handle_single(req) method = req["method"] if !method return err_resp(req, -32600, "No method provided on request") end # Special case - client is requesting the IDL bound to this server, so # we return it verbatim. No further validation is needed in this case. if method == "barrister-idl" return ok_resp(req, @contract.idl) end # Make sure we can find an interface and function on the IDL for this # request method string err_resp, iface, func = @contract.resolve_method(req) if err_resp != nil return err_resp end # Make sure that the params on the request match the IDL types err_resp = @contract.validate_params(req, func) if err_resp != nil return err_resp end params = [ ] if req["params"] params = req["params"] end # Make sure we have a handler bound to this Server for the interface. # If not, that means `server.add_handler` was not called for this interface # name. That's likely a misconfiguration. handler = @handlers[iface.name] if !handler return err_resp(req, -32000, "Server error. No handler is bound to interface #{iface.name}") end # Make sure that the handler has a method for the given function. if !handler.respond_to?(func.name) return err_resp(req, -32000, "Server error. Handler for #{iface.name} does not implement #{func.name}") end begin # Call the handler function. This is where your code gets invoked. result = handler.send(func.name, *params) # Verify that the handler function's return value matches the # correct type as specified in the IDL err_resp = @contract.validate_result(req, result, func) if err_resp != nil return err_resp else return ok_resp(req, result) end rescue RpcException => e # If the handler raised a RpcException, that's ok - return it unmodified. return err_resp(req, e.code, e.message, e.data) rescue => e # If any other error was raised, print it and return a generic error to the client puts e.inspect puts e.backtrace return err_resp(req, -32000, "Unknown error: #{e}") end end
[ "def", "handle_single", "(", "req", ")", "method", "=", "req", "[", "\"method\"", "]", "if", "!", "method", "return", "err_resp", "(", "req", ",", "-", "32600", ",", "\"No method provided on request\"", ")", "end", "if", "method", "==", "\"barrister-idl\"", "return", "ok_resp", "(", "req", ",", "@contract", ".", "idl", ")", "end", "err_resp", ",", "iface", ",", "func", "=", "@contract", ".", "resolve_method", "(", "req", ")", "if", "err_resp", "!=", "nil", "return", "err_resp", "end", "err_resp", "=", "@contract", ".", "validate_params", "(", "req", ",", "func", ")", "if", "err_resp", "!=", "nil", "return", "err_resp", "end", "params", "=", "[", "]", "if", "req", "[", "\"params\"", "]", "params", "=", "req", "[", "\"params\"", "]", "end", "handler", "=", "@handlers", "[", "iface", ".", "name", "]", "if", "!", "handler", "return", "err_resp", "(", "req", ",", "-", "32000", ",", "\"Server error. No handler is bound to interface #{iface.name}\"", ")", "end", "if", "!", "handler", ".", "respond_to?", "(", "func", ".", "name", ")", "return", "err_resp", "(", "req", ",", "-", "32000", ",", "\"Server error. Handler for #{iface.name} does not implement #{func.name}\"", ")", "end", "begin", "result", "=", "handler", ".", "send", "(", "func", ".", "name", ",", "*", "params", ")", "err_resp", "=", "@contract", ".", "validate_result", "(", "req", ",", "result", ",", "func", ")", "if", "err_resp", "!=", "nil", "return", "err_resp", "else", "return", "ok_resp", "(", "req", ",", "result", ")", "end", "rescue", "RpcException", "=>", "e", "return", "err_resp", "(", "req", ",", "e", ".", "code", ",", "e", ".", "message", ",", "e", ".", "data", ")", "rescue", "=>", "e", "puts", "e", ".", "inspect", "puts", "e", ".", "backtrace", "return", "err_resp", "(", "req", ",", "-", "32000", ",", "\"Unknown error: #{e}\"", ")", "end", "end" ]
Internal method that validates and executes a single request.
[ "Internal", "method", "that", "validates", "and", "executes", "a", "single", "request", "." ]
5606e7dc591762fc28a338dee48093aaaafb106e
https://github.com/coopernurse/barrister-ruby/blob/5606e7dc591762fc28a338dee48093aaaafb106e/lib/barrister.rb#L196-L260
train
coopernurse/barrister-ruby
lib/barrister.rb
Barrister.Client.init_proxies
def init_proxies singleton = class << self; self end @contract.interfaces.each do |iface| proxy = InterfaceProxy.new(self, iface) singleton.send :define_method, iface.name do return proxy end end end
ruby
def init_proxies singleton = class << self; self end @contract.interfaces.each do |iface| proxy = InterfaceProxy.new(self, iface) singleton.send :define_method, iface.name do return proxy end end end
[ "def", "init_proxies", "singleton", "=", "class", "<<", "self", ";", "self", "end", "@contract", ".", "interfaces", ".", "each", "do", "|", "iface", "|", "proxy", "=", "InterfaceProxy", ".", "new", "(", "self", ",", "iface", ")", "singleton", ".", "send", ":define_method", ",", "iface", ".", "name", "do", "return", "proxy", "end", "end", "end" ]
Internal method invoked by `initialize`. Iterates through the Contract and creates proxy classes for each interface.
[ "Internal", "method", "invoked", "by", "initialize", ".", "Iterates", "through", "the", "Contract", "and", "creates", "proxy", "classes", "for", "each", "interface", "." ]
5606e7dc591762fc28a338dee48093aaaafb106e
https://github.com/coopernurse/barrister-ruby/blob/5606e7dc591762fc28a338dee48093aaaafb106e/lib/barrister.rb#L322-L330
train
coopernurse/barrister-ruby
lib/barrister.rb
Barrister.Client.request
def request(method, params) req = { "jsonrpc" => "2.0", "id" => Barrister::rand_str(22), "method" => method } if params req["params"] = params end # We always validate that the method is valid err_resp, iface, func = @contract.resolve_method(req) if err_resp != nil return err_resp end if @validate_req err_resp = @contract.validate_params(req, func) if err_resp != nil return err_resp end end # This makes the request to the server resp = @trans.request(req) if @validate_result && resp != nil && resp.key?("result") err_resp = @contract.validate_result(req, resp["result"], func) if err_resp != nil resp = err_resp end end return resp end
ruby
def request(method, params) req = { "jsonrpc" => "2.0", "id" => Barrister::rand_str(22), "method" => method } if params req["params"] = params end # We always validate that the method is valid err_resp, iface, func = @contract.resolve_method(req) if err_resp != nil return err_resp end if @validate_req err_resp = @contract.validate_params(req, func) if err_resp != nil return err_resp end end # This makes the request to the server resp = @trans.request(req) if @validate_result && resp != nil && resp.key?("result") err_resp = @contract.validate_result(req, resp["result"], func) if err_resp != nil resp = err_resp end end return resp end
[ "def", "request", "(", "method", ",", "params", ")", "req", "=", "{", "\"jsonrpc\"", "=>", "\"2.0\"", ",", "\"id\"", "=>", "Barrister", "::", "rand_str", "(", "22", ")", ",", "\"method\"", "=>", "method", "}", "if", "params", "req", "[", "\"params\"", "]", "=", "params", "end", "err_resp", ",", "iface", ",", "func", "=", "@contract", ".", "resolve_method", "(", "req", ")", "if", "err_resp", "!=", "nil", "return", "err_resp", "end", "if", "@validate_req", "err_resp", "=", "@contract", ".", "validate_params", "(", "req", ",", "func", ")", "if", "err_resp", "!=", "nil", "return", "err_resp", "end", "end", "resp", "=", "@trans", ".", "request", "(", "req", ")", "if", "@validate_result", "&&", "resp", "!=", "nil", "&&", "resp", ".", "key?", "(", "\"result\"", ")", "err_resp", "=", "@contract", ".", "validate_result", "(", "req", ",", "resp", "[", "\"result\"", "]", ",", "func", ")", "if", "err_resp", "!=", "nil", "resp", "=", "err_resp", "end", "end", "return", "resp", "end" ]
Sends a JSON-RPC request. This method is automatically called by the proxy classes, so in practice you don't usually call it directly. However, it is available if you wish to avoid the use of proxy classes. * `method` - string of the method to invoke. Format: "interface.function". For example: "ContactService.saveContact" * `params` - parameters to pass to the function. Must be an Array
[ "Sends", "a", "JSON", "-", "RPC", "request", ".", "This", "method", "is", "automatically", "called", "by", "the", "proxy", "classes", "so", "in", "practice", "you", "don", "t", "usually", "call", "it", "directly", ".", "However", "it", "is", "available", "if", "you", "wish", "to", "avoid", "the", "use", "of", "proxy", "classes", "." ]
5606e7dc591762fc28a338dee48093aaaafb106e
https://github.com/coopernurse/barrister-ruby/blob/5606e7dc591762fc28a338dee48093aaaafb106e/lib/barrister.rb#L339-L369
train
coopernurse/barrister-ruby
lib/barrister.rb
Barrister.HttpTransport.request
def request(req) json_str = JSON::generate(req, { :ascii_only=>true }) http = Net::HTTP.new(@uri.host, @uri.port) request = Net::HTTP::Post.new(@uri.request_uri) request.body = json_str request["Content-Type"] = "application/json" response = http.request(request) if response.code != "200" raise RpcException.new(-32000, "Non-200 response #{response.code} from #{@url}") else return JSON::parse(response.body) end end
ruby
def request(req) json_str = JSON::generate(req, { :ascii_only=>true }) http = Net::HTTP.new(@uri.host, @uri.port) request = Net::HTTP::Post.new(@uri.request_uri) request.body = json_str request["Content-Type"] = "application/json" response = http.request(request) if response.code != "200" raise RpcException.new(-32000, "Non-200 response #{response.code} from #{@url}") else return JSON::parse(response.body) end end
[ "def", "request", "(", "req", ")", "json_str", "=", "JSON", "::", "generate", "(", "req", ",", "{", ":ascii_only", "=>", "true", "}", ")", "http", "=", "Net", "::", "HTTP", ".", "new", "(", "@uri", ".", "host", ",", "@uri", ".", "port", ")", "request", "=", "Net", "::", "HTTP", "::", "Post", ".", "new", "(", "@uri", ".", "request_uri", ")", "request", ".", "body", "=", "json_str", "request", "[", "\"Content-Type\"", "]", "=", "\"application/json\"", "response", "=", "http", ".", "request", "(", "request", ")", "if", "response", ".", "code", "!=", "\"200\"", "raise", "RpcException", ".", "new", "(", "-", "32000", ",", "\"Non-200 response #{response.code} from #{@url}\"", ")", "else", "return", "JSON", "::", "parse", "(", "response", ".", "body", ")", "end", "end" ]
Takes the URL to the server endpoint and parses it `request` is the only required method on a transport class. `req` is a JSON-RPC request with `id`, `method`, and optionally `params` slots. The transport is very simple, and does the following: * Serialize `req` to JSON. Make sure to use `:ascii_only=true` * POST the JSON string to the endpoint, setting the MIME type correctly * Deserialize the JSON response string * Return the deserialized hash
[ "Takes", "the", "URL", "to", "the", "server", "endpoint", "and", "parses", "it", "request", "is", "the", "only", "required", "method", "on", "a", "transport", "class", "." ]
5606e7dc591762fc28a338dee48093aaaafb106e
https://github.com/coopernurse/barrister-ruby/blob/5606e7dc591762fc28a338dee48093aaaafb106e/lib/barrister.rb#L395-L407
train
coopernurse/barrister-ruby
lib/barrister.rb
Barrister.BatchClient.send
def send if @trans.sent raise "Batch has already been sent!" end @trans.sent = true requests = @trans.requests if requests.length < 1 raise RpcException.new(-32600, "Batch cannot be empty") end # Send request batch to server resp_list = @parent.trans.request(requests) # Build a hash for the responses so we can re-order them # in request order. sorted = [ ] by_req_id = { } resp_list.each do |resp| by_req_id[resp["id"]] = resp end # Iterate through the requests in the batch and assemble # the sorted result array requests.each do |req| id = req["id"] resp = by_req_id[id] if !resp msg = "No result for request id: #{id}" resp = { "id" => id, "error" => { "code"=>-32603, "message" => msg } } end sorted << RpcResponse.new(req, resp) end return sorted end
ruby
def send if @trans.sent raise "Batch has already been sent!" end @trans.sent = true requests = @trans.requests if requests.length < 1 raise RpcException.new(-32600, "Batch cannot be empty") end # Send request batch to server resp_list = @parent.trans.request(requests) # Build a hash for the responses so we can re-order them # in request order. sorted = [ ] by_req_id = { } resp_list.each do |resp| by_req_id[resp["id"]] = resp end # Iterate through the requests in the batch and assemble # the sorted result array requests.each do |req| id = req["id"] resp = by_req_id[id] if !resp msg = "No result for request id: #{id}" resp = { "id" => id, "error" => { "code"=>-32603, "message" => msg } } end sorted << RpcResponse.new(req, resp) end return sorted end
[ "def", "send", "if", "@trans", ".", "sent", "raise", "\"Batch has already been sent!\"", "end", "@trans", ".", "sent", "=", "true", "requests", "=", "@trans", ".", "requests", "if", "requests", ".", "length", "<", "1", "raise", "RpcException", ".", "new", "(", "-", "32600", ",", "\"Batch cannot be empty\"", ")", "end", "resp_list", "=", "@parent", ".", "trans", ".", "request", "(", "requests", ")", "sorted", "=", "[", "]", "by_req_id", "=", "{", "}", "resp_list", ".", "each", "do", "|", "resp", "|", "by_req_id", "[", "resp", "[", "\"id\"", "]", "]", "=", "resp", "end", "requests", ".", "each", "do", "|", "req", "|", "id", "=", "req", "[", "\"id\"", "]", "resp", "=", "by_req_id", "[", "id", "]", "if", "!", "resp", "msg", "=", "\"No result for request id: #{id}\"", "resp", "=", "{", "\"id\"", "=>", "id", ",", "\"error\"", "=>", "{", "\"code\"", "=>", "-", "32603", ",", "\"message\"", "=>", "msg", "}", "}", "end", "sorted", "<<", "RpcResponse", ".", "new", "(", "req", ",", "resp", ")", "end", "return", "sorted", "end" ]
Sends the batch of requests to the server. Returns an Array of RpcResponse instances. The Array is ordered in the order of the requests made to the batch. Your code needs to check each element in the Array for errors. * Cannot be called more than once * Will raise RpcException if the batch is empty
[ "Sends", "the", "batch", "of", "requests", "to", "the", "server", "." ]
5606e7dc591762fc28a338dee48093aaaafb106e
https://github.com/coopernurse/barrister-ruby/blob/5606e7dc591762fc28a338dee48093aaaafb106e/lib/barrister.rb#L496-L532
train
coopernurse/barrister-ruby
lib/barrister.rb
Barrister.Contract.resolve_method
def resolve_method(req) method = req["method"] iface_name, func_name = Barrister::parse_method(method) if iface_name == nil return err_resp(req, -32601, "Method not found: #{method}") end iface = interface(iface_name) if !iface return err_resp(req, -32601, "Interface not found on IDL: #{iface_name}") end func = iface.function(func_name) if !func return err_resp(req, -32601, "Function #{func_name} does not exist on interface #{iface_name}") end return nil, iface, func end
ruby
def resolve_method(req) method = req["method"] iface_name, func_name = Barrister::parse_method(method) if iface_name == nil return err_resp(req, -32601, "Method not found: #{method}") end iface = interface(iface_name) if !iface return err_resp(req, -32601, "Interface not found on IDL: #{iface_name}") end func = iface.function(func_name) if !func return err_resp(req, -32601, "Function #{func_name} does not exist on interface #{iface_name}") end return nil, iface, func end
[ "def", "resolve_method", "(", "req", ")", "method", "=", "req", "[", "\"method\"", "]", "iface_name", ",", "func_name", "=", "Barrister", "::", "parse_method", "(", "method", ")", "if", "iface_name", "==", "nil", "return", "err_resp", "(", "req", ",", "-", "32601", ",", "\"Method not found: #{method}\"", ")", "end", "iface", "=", "interface", "(", "iface_name", ")", "if", "!", "iface", "return", "err_resp", "(", "req", ",", "-", "32601", ",", "\"Interface not found on IDL: #{iface_name}\"", ")", "end", "func", "=", "iface", ".", "function", "(", "func_name", ")", "if", "!", "func", "return", "err_resp", "(", "req", ",", "-", "32601", ",", "\"Function #{func_name} does not exist on interface #{iface_name}\"", ")", "end", "return", "nil", ",", "iface", ",", "func", "end" ]
Takes a JSON-RPC request hash, and returns a 3 element tuple. This is called as part of the request validation sequence. `0` - JSON-RPC response hash representing an error. nil if valid. `1` - Interface instance on this Contract that matches `req["method"]` `2` - Function instance on the Interface that matches `req["method"]`
[ "Takes", "a", "JSON", "-", "RPC", "request", "hash", "and", "returns", "a", "3", "element", "tuple", ".", "This", "is", "called", "as", "part", "of", "the", "request", "validation", "sequence", "." ]
5606e7dc591762fc28a338dee48093aaaafb106e
https://github.com/coopernurse/barrister-ruby/blob/5606e7dc591762fc28a338dee48093aaaafb106e/lib/barrister.rb#L620-L638
train
coopernurse/barrister-ruby
lib/barrister.rb
Barrister.Contract.validate_params
def validate_params(req, func) params = req["params"] if !params params = [] end e_params = func.params.length r_params = params.length if e_params != r_params msg = "Function #{func.name}: Param length #{r_params} != expected length: #{e_params}" return err_resp(req, -32602, msg) end for i in (0..(e_params-1)) expected = func.params[i] invalid = validate("Param[#{i}]", expected, expected["is_array"], params[i]) if invalid != nil return err_resp(req, -32602, invalid) end end # valid return nil end
ruby
def validate_params(req, func) params = req["params"] if !params params = [] end e_params = func.params.length r_params = params.length if e_params != r_params msg = "Function #{func.name}: Param length #{r_params} != expected length: #{e_params}" return err_resp(req, -32602, msg) end for i in (0..(e_params-1)) expected = func.params[i] invalid = validate("Param[#{i}]", expected, expected["is_array"], params[i]) if invalid != nil return err_resp(req, -32602, invalid) end end # valid return nil end
[ "def", "validate_params", "(", "req", ",", "func", ")", "params", "=", "req", "[", "\"params\"", "]", "if", "!", "params", "params", "=", "[", "]", "end", "e_params", "=", "func", ".", "params", ".", "length", "r_params", "=", "params", ".", "length", "if", "e_params", "!=", "r_params", "msg", "=", "\"Function #{func.name}: Param length #{r_params} != expected length: #{e_params}\"", "return", "err_resp", "(", "req", ",", "-", "32602", ",", "msg", ")", "end", "for", "i", "in", "(", "0", "..", "(", "e_params", "-", "1", ")", ")", "expected", "=", "func", ".", "params", "[", "i", "]", "invalid", "=", "validate", "(", "\"Param[#{i}]\"", ",", "expected", ",", "expected", "[", "\"is_array\"", "]", ",", "params", "[", "i", "]", ")", "if", "invalid", "!=", "nil", "return", "err_resp", "(", "req", ",", "-", "32602", ",", "invalid", ")", "end", "end", "return", "nil", "end" ]
Validates that the parameters on the JSON-RPC request match the types specified for this function Returns a JSON-RPC response hash if invalid, or nil if valid. * `req` - JSON-RPC request hash * `func` - Barrister::Function instance
[ "Validates", "that", "the", "parameters", "on", "the", "JSON", "-", "RPC", "request", "match", "the", "types", "specified", "for", "this", "function" ]
5606e7dc591762fc28a338dee48093aaaafb106e
https://github.com/coopernurse/barrister-ruby/blob/5606e7dc591762fc28a338dee48093aaaafb106e/lib/barrister.rb#L648-L670
train
coopernurse/barrister-ruby
lib/barrister.rb
Barrister.Contract.validate_result
def validate_result(req, result, func) invalid = validate("", func.returns, func.returns["is_array"], result) if invalid == nil return nil else return err_resp(req, -32001, invalid) end end
ruby
def validate_result(req, result, func) invalid = validate("", func.returns, func.returns["is_array"], result) if invalid == nil return nil else return err_resp(req, -32001, invalid) end end
[ "def", "validate_result", "(", "req", ",", "result", ",", "func", ")", "invalid", "=", "validate", "(", "\"\"", ",", "func", ".", "returns", ",", "func", ".", "returns", "[", "\"is_array\"", "]", ",", "result", ")", "if", "invalid", "==", "nil", "return", "nil", "else", "return", "err_resp", "(", "req", ",", "-", "32001", ",", "invalid", ")", "end", "end" ]
Validates that the result from a handler method invocation match the return type for this function Returns a JSON-RPC response hash if invalid, or nil if valid. * `req` - JSON-RPC request hash * `result` - Result object from the handler method call * `func` - Barrister::Function instance
[ "Validates", "that", "the", "result", "from", "a", "handler", "method", "invocation", "match", "the", "return", "type", "for", "this", "function" ]
5606e7dc591762fc28a338dee48093aaaafb106e
https://github.com/coopernurse/barrister-ruby/blob/5606e7dc591762fc28a338dee48093aaaafb106e/lib/barrister.rb#L681-L688
train
coopernurse/barrister-ruby
lib/barrister.rb
Barrister.Contract.validate
def validate(name, expected, expect_array, val) # If val is nil, then check if the IDL allows this type to be optional if val == nil if expected["optional"] return nil else return "#{name} cannot be null" end else exp_type = expected["type"] # If we expect an array, make sure that val is an Array, and then # recursively validate the elements in the array if expect_array if val.kind_of?(Array) stop = val.length - 1 for i in (0..stop) invalid = validate("#{name}[#{i}]", expected, false, val[i]) if invalid != nil return invalid end end return nil else return type_err(name, "[]"+expected["type"], val) end # Check the built in Barrister primitive types elsif exp_type == "string" if val.class == String return nil else return type_err(name, exp_type, val) end elsif exp_type == "bool" if val.class == TrueClass || val.class == FalseClass return nil else return type_err(name, exp_type, val) end elsif exp_type == "int" || exp_type == "float" if val.class == Integer || val.class == Fixnum || val.class == Bignum return nil elsif val.class == Float && exp_type == "float" return nil else return type_err(name, exp_type, val) end # Expected type is not an array or a Barrister primitive. # It must be a struct or an enum. else # Try to find a struct struct = @structs[exp_type] if struct if !val.kind_of?(Hash) return "#{name} #{exp_type} value must be a map/hash. not: " + val.class.name end s_field_keys = { } # Resolve all fields on the struct and its ancestors s_fields = all_struct_fields([], struct) # Validate that each field on the struct has a valid value s_fields.each do |f| fname = f["name"] invalid = validate("#{name}.#{fname}", f, f["is_array"], val[fname]) if invalid != nil return invalid end s_field_keys[fname] = 1 end # Validate that there are no extraneous elements on the value val.keys.each do |k| if !s_field_keys.key?(k) return "#{name}.#{k} is not a field in struct '#{exp_type}'" end end # Struct is valid return nil end # Try to find an enum enum = @enums[exp_type] if enum if val.class != String return "#{name} enum value must be a string. got: " + val.class.name end # Try to find an enum value that matches this val enum["values"].each do |en| if en["value"] == val return nil end end # Invalid return "#{name} #{val} is not a value in enum '#{exp_type}'" end # Unlikely branch - suggests the IDL is internally inconsistent return "#{name} unknown type: #{exp_type}" end # Panic if we have a branch unaccounted for. Indicates a Barrister bug. raise "Barrister ERROR: validate did not return for: #{name} #{expected}" end end
ruby
def validate(name, expected, expect_array, val) # If val is nil, then check if the IDL allows this type to be optional if val == nil if expected["optional"] return nil else return "#{name} cannot be null" end else exp_type = expected["type"] # If we expect an array, make sure that val is an Array, and then # recursively validate the elements in the array if expect_array if val.kind_of?(Array) stop = val.length - 1 for i in (0..stop) invalid = validate("#{name}[#{i}]", expected, false, val[i]) if invalid != nil return invalid end end return nil else return type_err(name, "[]"+expected["type"], val) end # Check the built in Barrister primitive types elsif exp_type == "string" if val.class == String return nil else return type_err(name, exp_type, val) end elsif exp_type == "bool" if val.class == TrueClass || val.class == FalseClass return nil else return type_err(name, exp_type, val) end elsif exp_type == "int" || exp_type == "float" if val.class == Integer || val.class == Fixnum || val.class == Bignum return nil elsif val.class == Float && exp_type == "float" return nil else return type_err(name, exp_type, val) end # Expected type is not an array or a Barrister primitive. # It must be a struct or an enum. else # Try to find a struct struct = @structs[exp_type] if struct if !val.kind_of?(Hash) return "#{name} #{exp_type} value must be a map/hash. not: " + val.class.name end s_field_keys = { } # Resolve all fields on the struct and its ancestors s_fields = all_struct_fields([], struct) # Validate that each field on the struct has a valid value s_fields.each do |f| fname = f["name"] invalid = validate("#{name}.#{fname}", f, f["is_array"], val[fname]) if invalid != nil return invalid end s_field_keys[fname] = 1 end # Validate that there are no extraneous elements on the value val.keys.each do |k| if !s_field_keys.key?(k) return "#{name}.#{k} is not a field in struct '#{exp_type}'" end end # Struct is valid return nil end # Try to find an enum enum = @enums[exp_type] if enum if val.class != String return "#{name} enum value must be a string. got: " + val.class.name end # Try to find an enum value that matches this val enum["values"].each do |en| if en["value"] == val return nil end end # Invalid return "#{name} #{val} is not a value in enum '#{exp_type}'" end # Unlikely branch - suggests the IDL is internally inconsistent return "#{name} unknown type: #{exp_type}" end # Panic if we have a branch unaccounted for. Indicates a Barrister bug. raise "Barrister ERROR: validate did not return for: #{name} #{expected}" end end
[ "def", "validate", "(", "name", ",", "expected", ",", "expect_array", ",", "val", ")", "if", "val", "==", "nil", "if", "expected", "[", "\"optional\"", "]", "return", "nil", "else", "return", "\"#{name} cannot be null\"", "end", "else", "exp_type", "=", "expected", "[", "\"type\"", "]", "if", "expect_array", "if", "val", ".", "kind_of?", "(", "Array", ")", "stop", "=", "val", ".", "length", "-", "1", "for", "i", "in", "(", "0", "..", "stop", ")", "invalid", "=", "validate", "(", "\"#{name}[#{i}]\"", ",", "expected", ",", "false", ",", "val", "[", "i", "]", ")", "if", "invalid", "!=", "nil", "return", "invalid", "end", "end", "return", "nil", "else", "return", "type_err", "(", "name", ",", "\"[]\"", "+", "expected", "[", "\"type\"", "]", ",", "val", ")", "end", "elsif", "exp_type", "==", "\"string\"", "if", "val", ".", "class", "==", "String", "return", "nil", "else", "return", "type_err", "(", "name", ",", "exp_type", ",", "val", ")", "end", "elsif", "exp_type", "==", "\"bool\"", "if", "val", ".", "class", "==", "TrueClass", "||", "val", ".", "class", "==", "FalseClass", "return", "nil", "else", "return", "type_err", "(", "name", ",", "exp_type", ",", "val", ")", "end", "elsif", "exp_type", "==", "\"int\"", "||", "exp_type", "==", "\"float\"", "if", "val", ".", "class", "==", "Integer", "||", "val", ".", "class", "==", "Fixnum", "||", "val", ".", "class", "==", "Bignum", "return", "nil", "elsif", "val", ".", "class", "==", "Float", "&&", "exp_type", "==", "\"float\"", "return", "nil", "else", "return", "type_err", "(", "name", ",", "exp_type", ",", "val", ")", "end", "else", "struct", "=", "@structs", "[", "exp_type", "]", "if", "struct", "if", "!", "val", ".", "kind_of?", "(", "Hash", ")", "return", "\"#{name} #{exp_type} value must be a map/hash. not: \"", "+", "val", ".", "class", ".", "name", "end", "s_field_keys", "=", "{", "}", "s_fields", "=", "all_struct_fields", "(", "[", "]", ",", "struct", ")", "s_fields", ".", "each", "do", "|", "f", "|", "fname", "=", "f", "[", "\"name\"", "]", "invalid", "=", "validate", "(", "\"#{name}.#{fname}\"", ",", "f", ",", "f", "[", "\"is_array\"", "]", ",", "val", "[", "fname", "]", ")", "if", "invalid", "!=", "nil", "return", "invalid", "end", "s_field_keys", "[", "fname", "]", "=", "1", "end", "val", ".", "keys", ".", "each", "do", "|", "k", "|", "if", "!", "s_field_keys", ".", "key?", "(", "k", ")", "return", "\"#{name}.#{k} is not a field in struct '#{exp_type}'\"", "end", "end", "return", "nil", "end", "enum", "=", "@enums", "[", "exp_type", "]", "if", "enum", "if", "val", ".", "class", "!=", "String", "return", "\"#{name} enum value must be a string. got: \"", "+", "val", ".", "class", ".", "name", "end", "enum", "[", "\"values\"", "]", ".", "each", "do", "|", "en", "|", "if", "en", "[", "\"value\"", "]", "==", "val", "return", "nil", "end", "end", "return", "\"#{name} #{val} is not a value in enum '#{exp_type}'\"", "end", "return", "\"#{name} unknown type: #{exp_type}\"", "end", "raise", "\"Barrister ERROR: validate did not return for: #{name} #{expected}\"", "end", "end" ]
Validates the type for a single value. This method is recursive when validating arrays or structs. Returns a string describing the validation error if invalid, or nil if valid * `name` - string to prefix onto the validation error * `expected` - expected type (hash) * `expect_array` - if true, we expect val to be an Array * `val` - value to validate
[ "Validates", "the", "type", "for", "a", "single", "value", ".", "This", "method", "is", "recursive", "when", "validating", "arrays", "or", "structs", "." ]
5606e7dc591762fc28a338dee48093aaaafb106e
https://github.com/coopernurse/barrister-ruby/blob/5606e7dc591762fc28a338dee48093aaaafb106e/lib/barrister.rb#L700-L812
train
coopernurse/barrister-ruby
lib/barrister.rb
Barrister.Contract.all_struct_fields
def all_struct_fields(arr, struct) struct["fields"].each do |f| arr << f end if struct["extends"] parent = @structs[struct["extends"]] if parent return all_struct_fields(arr, parent) end end return arr end
ruby
def all_struct_fields(arr, struct) struct["fields"].each do |f| arr << f end if struct["extends"] parent = @structs[struct["extends"]] if parent return all_struct_fields(arr, parent) end end return arr end
[ "def", "all_struct_fields", "(", "arr", ",", "struct", ")", "struct", "[", "\"fields\"", "]", ".", "each", "do", "|", "f", "|", "arr", "<<", "f", "end", "if", "struct", "[", "\"extends\"", "]", "parent", "=", "@structs", "[", "struct", "[", "\"extends\"", "]", "]", "if", "parent", "return", "all_struct_fields", "(", "arr", ",", "parent", ")", "end", "end", "return", "arr", "end" ]
Recursively resolves all fields for the struct and its ancestors Returns an Array with all the fields
[ "Recursively", "resolves", "all", "fields", "for", "the", "struct", "and", "its", "ancestors" ]
5606e7dc591762fc28a338dee48093aaaafb106e
https://github.com/coopernurse/barrister-ruby/blob/5606e7dc591762fc28a338dee48093aaaafb106e/lib/barrister.rb#L817-L830
train
moove-it/rusen
lib/rusen/notifier.rb
Rusen.Notifier.notify
def notify(exception, request = {}, environment = {}, session = {}) begin notification = Notification.new(exception, request, environment, session) @notifiers.each do |notifier| notifier.notify(notification) end # We need to ignore all the exceptions thrown by the notifiers. rescue Exception warn('Rusen: Some or all the notifiers failed to sent the notification.') end end
ruby
def notify(exception, request = {}, environment = {}, session = {}) begin notification = Notification.new(exception, request, environment, session) @notifiers.each do |notifier| notifier.notify(notification) end # We need to ignore all the exceptions thrown by the notifiers. rescue Exception warn('Rusen: Some or all the notifiers failed to sent the notification.') end end
[ "def", "notify", "(", "exception", ",", "request", "=", "{", "}", ",", "environment", "=", "{", "}", ",", "session", "=", "{", "}", ")", "begin", "notification", "=", "Notification", ".", "new", "(", "exception", ",", "request", ",", "environment", ",", "session", ")", "@notifiers", ".", "each", "do", "|", "notifier", "|", "notifier", ".", "notify", "(", "notification", ")", "end", "rescue", "Exception", "warn", "(", "'Rusen: Some or all the notifiers failed to sent the notification.'", ")", "end", "end" ]
Sends a notification to the configured outputs. @param [Exception] exception The error. @param [Hash<Object, Object>] request The request params @param [Hash<Object, Object>] environment The environment status. @param [Hash<Object, Object>] session The session status.
[ "Sends", "a", "notification", "to", "the", "configured", "outputs", "." ]
6cef7b47017844b2e680baa19a28bff17bb68da2
https://github.com/moove-it/rusen/blob/6cef7b47017844b2e680baa19a28bff17bb68da2/lib/rusen/notifier.rb#L39-L51
train
reset/chozo
lib/chozo/hashie_ext/mash.rb
Hashie.Mash.[]=
def []=(key, value) coerced_value = coercion(key).present? ? coercion(key).call(value) : value old_setter(key, coerced_value) end
ruby
def []=(key, value) coerced_value = coercion(key).present? ? coercion(key).call(value) : value old_setter(key, coerced_value) end
[ "def", "[]=", "(", "key", ",", "value", ")", "coerced_value", "=", "coercion", "(", "key", ")", ".", "present?", "?", "coercion", "(", "key", ")", ".", "call", "(", "value", ")", ":", "value", "old_setter", "(", "key", ",", "coerced_value", ")", "end" ]
Override setter to coerce the given value if a coercion is defined
[ "Override", "setter", "to", "coerce", "the", "given", "value", "if", "a", "coercion", "is", "defined" ]
ba88aff29bef4b2f56090a8ad1a4ba5a165786e8
https://github.com/reset/chozo/blob/ba88aff29bef4b2f56090a8ad1a4ba5a165786e8/lib/chozo/hashie_ext/mash.rb#L23-L26
train
movitto/reterm
lib/reterm/panel.rb
RETerm.Panel.show
def show Ncurses::Panel.top_panel(@panel) update_reterm @@registry.values.each { |panel| if panel == self dispatch :panel_show else panel.dispatch :panel_hide end } end
ruby
def show Ncurses::Panel.top_panel(@panel) update_reterm @@registry.values.each { |panel| if panel == self dispatch :panel_show else panel.dispatch :panel_hide end } end
[ "def", "show", "Ncurses", "::", "Panel", ".", "top_panel", "(", "@panel", ")", "update_reterm", "@@registry", ".", "values", ".", "each", "{", "|", "panel", "|", "if", "panel", "==", "self", "dispatch", ":panel_show", "else", "panel", ".", "dispatch", ":panel_hide", "end", "}", "end" ]
Initialize panel from the given window. This maintains an internal registry of panels created for event dispatching purposes Render this panel by surfacing it ot hte top of the stack
[ "Initialize", "panel", "from", "the", "given", "window", "." ]
3e78c64e677f69b22f00dc89c2b515b9188c5e15
https://github.com/movitto/reterm/blob/3e78c64e677f69b22f00dc89c2b515b9188c5e15/lib/reterm/panel.rb#L24-L35
train
niho/related
lib/related/helpers.rb
Related.Helpers.generate_id
def generate_id Base64.encode64( Digest::MD5.digest("#{Time.now}-#{rand}") ).gsub('/','x').gsub('+','y').gsub('=','').strip end
ruby
def generate_id Base64.encode64( Digest::MD5.digest("#{Time.now}-#{rand}") ).gsub('/','x').gsub('+','y').gsub('=','').strip end
[ "def", "generate_id", "Base64", ".", "encode64", "(", "Digest", "::", "MD5", ".", "digest", "(", "\"#{Time.now}-#{rand}\"", ")", ")", ".", "gsub", "(", "'/'", ",", "'x'", ")", ".", "gsub", "(", "'+'", ",", "'y'", ")", ".", "gsub", "(", "'='", ",", "''", ")", ".", "strip", "end" ]
Generate a unique id
[ "Generate", "a", "unique", "id" ]
c18d66911c4f08ed7422d2122bc2fbfdb0274c8f
https://github.com/niho/related/blob/c18d66911c4f08ed7422d2122bc2fbfdb0274c8f/lib/related/helpers.rb#L8-L12
train
reset/chozo
lib/chozo/mixin/params_validate.rb
Chozo::Mixin.ParamsValidate._pv_opts_lookup
def _pv_opts_lookup(opts, key) if opts.has_key?(key.to_s) opts[key.to_s] elsif opts.has_key?(key.to_sym) opts[key.to_sym] else nil end end
ruby
def _pv_opts_lookup(opts, key) if opts.has_key?(key.to_s) opts[key.to_s] elsif opts.has_key?(key.to_sym) opts[key.to_sym] else nil end end
[ "def", "_pv_opts_lookup", "(", "opts", ",", "key", ")", "if", "opts", ".", "has_key?", "(", "key", ".", "to_s", ")", "opts", "[", "key", ".", "to_s", "]", "elsif", "opts", ".", "has_key?", "(", "key", ".", "to_sym", ")", "opts", "[", "key", ".", "to_sym", "]", "else", "nil", "end", "end" ]
Return the value of a parameter, or nil if it doesn't exist.
[ "Return", "the", "value", "of", "a", "parameter", "or", "nil", "if", "it", "doesn", "t", "exist", "." ]
ba88aff29bef4b2f56090a8ad1a4ba5a165786e8
https://github.com/reset/chozo/blob/ba88aff29bef4b2f56090a8ad1a4ba5a165786e8/lib/chozo/mixin/params_validate.rb#L91-L99
train
reset/chozo
lib/chozo/mixin/params_validate.rb
Chozo::Mixin.ParamsValidate._pv_required
def _pv_required(opts, key, is_required=true) if is_required if (opts.has_key?(key.to_s) && !opts[key.to_s].nil?) || (opts.has_key?(key.to_sym) && !opts[key.to_sym].nil?) true else raise ValidationFailed, "Required argument #{key} is missing!" end end end
ruby
def _pv_required(opts, key, is_required=true) if is_required if (opts.has_key?(key.to_s) && !opts[key.to_s].nil?) || (opts.has_key?(key.to_sym) && !opts[key.to_sym].nil?) true else raise ValidationFailed, "Required argument #{key} is missing!" end end end
[ "def", "_pv_required", "(", "opts", ",", "key", ",", "is_required", "=", "true", ")", "if", "is_required", "if", "(", "opts", ".", "has_key?", "(", "key", ".", "to_s", ")", "&&", "!", "opts", "[", "key", ".", "to_s", "]", ".", "nil?", ")", "||", "(", "opts", ".", "has_key?", "(", "key", ".", "to_sym", ")", "&&", "!", "opts", "[", "key", ".", "to_sym", "]", ".", "nil?", ")", "true", "else", "raise", "ValidationFailed", ",", "\"Required argument #{key} is missing!\"", "end", "end", "end" ]
Raise an exception if the parameter is not found.
[ "Raise", "an", "exception", "if", "the", "parameter", "is", "not", "found", "." ]
ba88aff29bef4b2f56090a8ad1a4ba5a165786e8
https://github.com/reset/chozo/blob/ba88aff29bef4b2f56090a8ad1a4ba5a165786e8/lib/chozo/mixin/params_validate.rb#L102-L111
train
reset/chozo
lib/chozo/mixin/params_validate.rb
Chozo::Mixin.ParamsValidate._pv_respond_to
def _pv_respond_to(opts, key, method_name_list) value = _pv_opts_lookup(opts, key) unless value.nil? Array(method_name_list).each do |method_name| unless value.respond_to?(method_name) raise ValidationFailed, "Option #{key} must have a #{method_name} method!" end end end end
ruby
def _pv_respond_to(opts, key, method_name_list) value = _pv_opts_lookup(opts, key) unless value.nil? Array(method_name_list).each do |method_name| unless value.respond_to?(method_name) raise ValidationFailed, "Option #{key} must have a #{method_name} method!" end end end end
[ "def", "_pv_respond_to", "(", "opts", ",", "key", ",", "method_name_list", ")", "value", "=", "_pv_opts_lookup", "(", "opts", ",", "key", ")", "unless", "value", ".", "nil?", "Array", "(", "method_name_list", ")", ".", "each", "do", "|", "method_name", "|", "unless", "value", ".", "respond_to?", "(", "method_name", ")", "raise", "ValidationFailed", ",", "\"Option #{key} must have a #{method_name} method!\"", "end", "end", "end", "end" ]
Raise an exception if the parameter does not respond to a given set of methods.
[ "Raise", "an", "exception", "if", "the", "parameter", "does", "not", "respond", "to", "a", "given", "set", "of", "methods", "." ]
ba88aff29bef4b2f56090a8ad1a4ba5a165786e8
https://github.com/reset/chozo/blob/ba88aff29bef4b2f56090a8ad1a4ba5a165786e8/lib/chozo/mixin/params_validate.rb#L141-L150
train
reset/chozo
lib/chozo/mixin/params_validate.rb
Chozo::Mixin.ParamsValidate._pv_default
def _pv_default(opts, key, default_value) value = _pv_opts_lookup(opts, key) if value == nil opts[key] = default_value end end
ruby
def _pv_default(opts, key, default_value) value = _pv_opts_lookup(opts, key) if value == nil opts[key] = default_value end end
[ "def", "_pv_default", "(", "opts", ",", "key", ",", "default_value", ")", "value", "=", "_pv_opts_lookup", "(", "opts", ",", "key", ")", "if", "value", "==", "nil", "opts", "[", "key", "]", "=", "default_value", "end", "end" ]
Assign a default value to a parameter.
[ "Assign", "a", "default", "value", "to", "a", "parameter", "." ]
ba88aff29bef4b2f56090a8ad1a4ba5a165786e8
https://github.com/reset/chozo/blob/ba88aff29bef4b2f56090a8ad1a4ba5a165786e8/lib/chozo/mixin/params_validate.rb#L171-L176
train
reset/chozo
lib/chozo/mixin/params_validate.rb
Chozo::Mixin.ParamsValidate._pv_regex
def _pv_regex(opts, key, regex) value = _pv_opts_lookup(opts, key) if value != nil passes = false [ regex ].flatten.each do |r| if value != nil if r.match(value.to_s) passes = true end end end unless passes raise ValidationFailed, "Option #{key}'s value #{value} does not match regular expression #{regex.inspect}" end end end
ruby
def _pv_regex(opts, key, regex) value = _pv_opts_lookup(opts, key) if value != nil passes = false [ regex ].flatten.each do |r| if value != nil if r.match(value.to_s) passes = true end end end unless passes raise ValidationFailed, "Option #{key}'s value #{value} does not match regular expression #{regex.inspect}" end end end
[ "def", "_pv_regex", "(", "opts", ",", "key", ",", "regex", ")", "value", "=", "_pv_opts_lookup", "(", "opts", ",", "key", ")", "if", "value", "!=", "nil", "passes", "=", "false", "[", "regex", "]", ".", "flatten", ".", "each", "do", "|", "r", "|", "if", "value", "!=", "nil", "if", "r", ".", "match", "(", "value", ".", "to_s", ")", "passes", "=", "true", "end", "end", "end", "unless", "passes", "raise", "ValidationFailed", ",", "\"Option #{key}'s value #{value} does not match regular expression #{regex.inspect}\"", "end", "end", "end" ]
Check a parameter against a regular expression.
[ "Check", "a", "parameter", "against", "a", "regular", "expression", "." ]
ba88aff29bef4b2f56090a8ad1a4ba5a165786e8
https://github.com/reset/chozo/blob/ba88aff29bef4b2f56090a8ad1a4ba5a165786e8/lib/chozo/mixin/params_validate.rb#L179-L194
train
reset/chozo
lib/chozo/mixin/params_validate.rb
Chozo::Mixin.ParamsValidate._pv_callbacks
def _pv_callbacks(opts, key, callbacks) raise ArgumentError, "Callback list must be a hash!" unless callbacks.kind_of?(Hash) value = _pv_opts_lookup(opts, key) if value != nil callbacks.each do |message, zeproc| if zeproc.call(value) != true raise ValidationFailed, "Option #{key}'s value #{value} #{message}!" end end end end
ruby
def _pv_callbacks(opts, key, callbacks) raise ArgumentError, "Callback list must be a hash!" unless callbacks.kind_of?(Hash) value = _pv_opts_lookup(opts, key) if value != nil callbacks.each do |message, zeproc| if zeproc.call(value) != true raise ValidationFailed, "Option #{key}'s value #{value} #{message}!" end end end end
[ "def", "_pv_callbacks", "(", "opts", ",", "key", ",", "callbacks", ")", "raise", "ArgumentError", ",", "\"Callback list must be a hash!\"", "unless", "callbacks", ".", "kind_of?", "(", "Hash", ")", "value", "=", "_pv_opts_lookup", "(", "opts", ",", "key", ")", "if", "value", "!=", "nil", "callbacks", ".", "each", "do", "|", "message", ",", "zeproc", "|", "if", "zeproc", ".", "call", "(", "value", ")", "!=", "true", "raise", "ValidationFailed", ",", "\"Option #{key}'s value #{value} #{message}!\"", "end", "end", "end", "end" ]
Check a parameter against a hash of proc's.
[ "Check", "a", "parameter", "against", "a", "hash", "of", "proc", "s", "." ]
ba88aff29bef4b2f56090a8ad1a4ba5a165786e8
https://github.com/reset/chozo/blob/ba88aff29bef4b2f56090a8ad1a4ba5a165786e8/lib/chozo/mixin/params_validate.rb#L197-L207
train
reset/chozo
lib/chozo/mixin/params_validate.rb
Chozo::Mixin.ParamsValidate._pv_name_attribute
def _pv_name_attribute(opts, key, is_name_attribute=true) if is_name_attribute if opts[key] == nil opts[key] = self.instance_variable_get("@name") end end end
ruby
def _pv_name_attribute(opts, key, is_name_attribute=true) if is_name_attribute if opts[key] == nil opts[key] = self.instance_variable_get("@name") end end end
[ "def", "_pv_name_attribute", "(", "opts", ",", "key", ",", "is_name_attribute", "=", "true", ")", "if", "is_name_attribute", "if", "opts", "[", "key", "]", "==", "nil", "opts", "[", "key", "]", "=", "self", ".", "instance_variable_get", "(", "\"@name\"", ")", "end", "end", "end" ]
Allow a parameter to default to @name
[ "Allow", "a", "parameter", "to", "default", "to" ]
ba88aff29bef4b2f56090a8ad1a4ba5a165786e8
https://github.com/reset/chozo/blob/ba88aff29bef4b2f56090a8ad1a4ba5a165786e8/lib/chozo/mixin/params_validate.rb#L210-L216
train
puppetlabs/beaker-answers
lib/beaker-answers/versions/version20162.rb
BeakerAnswers.Version20162.answer_hiera
def answer_hiera # Render pretty JSON, because it is a subset of HOCON json = JSON.pretty_generate(answers) hocon = Hocon::Parser::ConfigDocumentFactory.parse_string(json) hocon.render end
ruby
def answer_hiera # Render pretty JSON, because it is a subset of HOCON json = JSON.pretty_generate(answers) hocon = Hocon::Parser::ConfigDocumentFactory.parse_string(json) hocon.render end
[ "def", "answer_hiera", "json", "=", "JSON", ".", "pretty_generate", "(", "answers", ")", "hocon", "=", "Hocon", "::", "Parser", "::", "ConfigDocumentFactory", ".", "parse_string", "(", "json", ")", "hocon", ".", "render", "end" ]
This converts a data hash provided by answers, and returns a Puppet Enterprise compatible hiera config file ready for use. @return [String] a string of parseable hocon @example Generating an answer file for a series of hosts hosts.each do |host| answers = Beaker::Answers.new("2.0", hosts, "master") create_remote_file host, "/mypath/answer", answers.answer_hiera end
[ "This", "converts", "a", "data", "hash", "provided", "by", "answers", "and", "returns", "a", "Puppet", "Enterprise", "compatible", "hiera", "config", "file", "ready", "for", "use", "." ]
3193bf986fd1842f2c7d8940a88df36db4200f3f
https://github.com/puppetlabs/beaker-answers/blob/3193bf986fd1842f2c7d8940a88df36db4200f3f/lib/beaker-answers/versions/version20162.rb#L99-L104
train
flyertools/tripit
lib/trip_it/base.rb
TripIt.Base.convertDT
def convertDT(tpitDT) return nil if tpitDT.nil? date = tpitDT["date"] time = tpitDT["time"] offset = tpitDT["utc_offset"] if time.nil? # Just return a date Date.parse(date) elsif date.nil? # Or just a time Time.parse(time) else # Ideally both DateTime.parse("#{date}T#{time}#{offset}") end end
ruby
def convertDT(tpitDT) return nil if tpitDT.nil? date = tpitDT["date"] time = tpitDT["time"] offset = tpitDT["utc_offset"] if time.nil? # Just return a date Date.parse(date) elsif date.nil? # Or just a time Time.parse(time) else # Ideally both DateTime.parse("#{date}T#{time}#{offset}") end end
[ "def", "convertDT", "(", "tpitDT", ")", "return", "nil", "if", "tpitDT", ".", "nil?", "date", "=", "tpitDT", "[", "\"date\"", "]", "time", "=", "tpitDT", "[", "\"time\"", "]", "offset", "=", "tpitDT", "[", "\"utc_offset\"", "]", "if", "time", ".", "nil?", "Date", ".", "parse", "(", "date", ")", "elsif", "date", ".", "nil?", "Time", ".", "parse", "(", "time", ")", "else", "DateTime", ".", "parse", "(", "\"#{date}T#{time}#{offset}\"", ")", "end", "end" ]
Convert a TripIt DateTime Object to a Ruby DateTime Object
[ "Convert", "a", "TripIt", "DateTime", "Object", "to", "a", "Ruby", "DateTime", "Object" ]
8d0c1d19c5c8ec22faafee73389e50c6da4d7a5a
https://github.com/flyertools/tripit/blob/8d0c1d19c5c8ec22faafee73389e50c6da4d7a5a/lib/trip_it/base.rb#L28-L43
train
holtrop/rscons
lib/rscons/builder.rb
Rscons.Builder.standard_build
def standard_build(short_cmd_string, target, command, sources, env, cache) unless cache.up_to_date?(target, command, sources, env) unless Rscons.phony_target?(target) cache.mkdir_p(File.dirname(target)) FileUtils.rm_f(target) end return false unless env.execute(short_cmd_string, command) cache.register_build(target, command, sources, env) end target end
ruby
def standard_build(short_cmd_string, target, command, sources, env, cache) unless cache.up_to_date?(target, command, sources, env) unless Rscons.phony_target?(target) cache.mkdir_p(File.dirname(target)) FileUtils.rm_f(target) end return false unless env.execute(short_cmd_string, command) cache.register_build(target, command, sources, env) end target end
[ "def", "standard_build", "(", "short_cmd_string", ",", "target", ",", "command", ",", "sources", ",", "env", ",", "cache", ")", "unless", "cache", ".", "up_to_date?", "(", "target", ",", "command", ",", "sources", ",", "env", ")", "unless", "Rscons", ".", "phony_target?", "(", "target", ")", "cache", ".", "mkdir_p", "(", "File", ".", "dirname", "(", "target", ")", ")", "FileUtils", ".", "rm_f", "(", "target", ")", "end", "return", "false", "unless", "env", ".", "execute", "(", "short_cmd_string", ",", "command", ")", "cache", ".", "register_build", "(", "target", ",", "command", ",", "sources", ",", "env", ")", "end", "target", "end" ]
Check if the cache is up to date for the target and if not execute the build command. This method does not support parallelization. @param short_cmd_string [String] Short description of build action to be printed when env.echo == :short. @param target [String] Name of the target file. @param command [Array<String>] The command to execute to build the target. @param sources [Array<String>] Source file name(s). @param env [Environment] The Environment executing the builder. @param cache [Cache] The Cache object. @return [String,false] The name of the target on success or false on failure.
[ "Check", "if", "the", "cache", "is", "up", "to", "date", "for", "the", "target", "and", "if", "not", "execute", "the", "build", "command", ".", "This", "method", "does", "not", "support", "parallelization", "." ]
4967f89a769a7b5c6ca91377526e3f53ceabd6a3
https://github.com/holtrop/rscons/blob/4967f89a769a7b5c6ca91377526e3f53ceabd6a3/lib/rscons/builder.rb#L207-L217
train
movitto/reterm
lib/reterm/window.rb
RETerm.Window.finalize!
def finalize! erase @@registry.delete(self) children.each { |c| del_child c } cdk_scr.destroy if cdk? component.finalize! if component? end
ruby
def finalize! erase @@registry.delete(self) children.each { |c| del_child c } cdk_scr.destroy if cdk? component.finalize! if component? end
[ "def", "finalize!", "erase", "@@registry", ".", "delete", "(", "self", ")", "children", ".", "each", "{", "|", "c", "|", "del_child", "c", "}", "cdk_scr", ".", "destroy", "if", "cdk?", "component", ".", "finalize!", "if", "component?", "end" ]
Invoke window finalization routine by destroying it and all children
[ "Invoke", "window", "finalization", "routine", "by", "destroying", "it", "and", "all", "children" ]
3e78c64e677f69b22f00dc89c2b515b9188c5e15
https://github.com/movitto/reterm/blob/3e78c64e677f69b22f00dc89c2b515b9188c5e15/lib/reterm/window.rb#L237-L247
train
movitto/reterm
lib/reterm/window.rb
RETerm.Window.child_containing
def child_containing(x, y, z) found = nil children.find { |c| next if found # recursively descend into layout children if c.component.kind_of?(Layout) found = c.child_containing(x, y, z) else found = c.total_x <= x && c.total_y <= y && # c.z >= z (c.total_x + c.cols) >= x && (c.total_y + c.rows) >= y found = c if found end } found end
ruby
def child_containing(x, y, z) found = nil children.find { |c| next if found # recursively descend into layout children if c.component.kind_of?(Layout) found = c.child_containing(x, y, z) else found = c.total_x <= x && c.total_y <= y && # c.z >= z (c.total_x + c.cols) >= x && (c.total_y + c.rows) >= y found = c if found end } found end
[ "def", "child_containing", "(", "x", ",", "y", ",", "z", ")", "found", "=", "nil", "children", ".", "find", "{", "|", "c", "|", "next", "if", "found", "if", "c", ".", "component", ".", "kind_of?", "(", "Layout", ")", "found", "=", "c", ".", "child_containing", "(", "x", ",", "y", ",", "z", ")", "else", "found", "=", "c", ".", "total_x", "<=", "x", "&&", "c", ".", "total_y", "<=", "y", "&&", "(", "c", ".", "total_x", "+", "c", ".", "cols", ")", ">=", "x", "&&", "(", "c", ".", "total_y", "+", "c", ".", "rows", ")", ">=", "y", "found", "=", "c", "if", "found", "end", "}", "found", "end" ]
Return child containing specified screen coordiantes, else nil
[ "Return", "child", "containing", "specified", "screen", "coordiantes", "else", "nil" ]
3e78c64e677f69b22f00dc89c2b515b9188c5e15
https://github.com/movitto/reterm/blob/3e78c64e677f69b22f00dc89c2b515b9188c5e15/lib/reterm/window.rb#L336-L354
train